Java Methods

In the previous chapters, we often usedSystem.out.println(), so what is it?

  • println() is a method.
  • System is a system class.
  • out is the standard output object.

This statement is used to call the println() method in the standard output object out of the system class System.

So what is a method?

A Java method is a collection of statements that together perform a function.

  • A method is an ordered combination of steps to solve a class of problems.
  • A method is contained in a class or object.
  • A method is created in the program and referenced elsewhere.

Advantages of Methods

  • 1. It makes the program shorter and clearer.
  • 2. It is beneficial for program maintenance.
  • 3. It can improve the efficiency of program development.
  • 4. It improves code reusability.

Method Naming Rules

  • 1. The first word of a method name should begin with a lowercase letter, and subsequent words should begin with an uppercase letter, without using separators. For example:addPerson。
  • 2. Underscores may appear in JUnit test method names to separate logical components of the name. A typical pattern is:test<MethodUnderTest>_<state>, for exampletestPop_emptyStack。

Method Definition

In general, defining a method includes the following syntax:

modifier return value type method name(parameter type parameter name){... method body ...returnreturn value;}

A method consists of a method header and a method body. Below are all the parts of a method:

  • Modifiers:Modifiers are optional and tell the compiler how to call the method. They define the access type of the method.
  • Return value type:A method may return a value. returnValueType is the data type of the value returned by the method. Some methods perform the required operation but do not return a value. In this case, returnValueType is the keywordvoid。
  • Method name:It is the actual name of the method. The method name and parameter table together constitute the method signature.
  • Parameter type:Parameters act like placeholders. When a method is called, a value is passed to the parameter. This value is called an actual argument or variable. The parameter list refers to the parameter types, order, and number of parameters. Parameters are optional; a method may contain no parameters.
  • Method body:The method body contains concrete statements that define the functionality of the method.

For example:

public static int age(int birthday){...}

There can be multiple parameters:

static float interest(float principal, int year){...}

Note:In some other languages, methods are referred to as procedures and functions. A method that returns a non-void value is called a function; a method that returns a void value is called a procedure.

Example

The following method contains 2 parameters, num1 and num2, and it returns the maximum of these two parameters.

/** Returns the larger value of two integer variables*/ public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; }

A more concise way to write it (ternary operator):

public static int max(int num1, int num2) { return num1 > num2 ? num1 : num2; }

Method Invocation

Java supports two ways to call a method, depending on whether the method returns a value.

When a program calls a method, program control is transferred to the called method. Control is returned to the program when the called method executes a return statement or reaches the closing brace of the method body.

When a method returns a value, the method call is usually treated as a value. For example:

int larger = max(30, 40);

If a method returns void, the method call must be a statement. For example, the method println returns void. The following call is a statement:

System.out.println("Welcome to Example!");

Example

The following example demonstrates how to define a method and how to call it:

TestMax.java file code:

public class TestMax { /** Main method*/ public static void main(String[] args) { int i = 5; int j = 2; int k = max(i, j); System.out.println( i + "and" + j + "Compare, the maximum value is:" + k); } /** Returns the larger of two integer variables*/ public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; } }

The above example compiles and runs with the following result:

5 和 2 比较,最大值是:5

This program contains a main method and a max method. The main method is called by the JVM. Apart from that, the main method is no different from other methods.

The header of the main method is fixed, as shown in the example. It has modifiers public and static, returns a void value, the method name is main, and it takes a String[] type parameter. String[] indicates that the parameter is an array of strings.


The void Keyword

This section explains how to declare and call a void method.

The following example declares a method named printGrade and calls it to print the given score.

Example

TestVoidMethod.java file code:

public class TestVoidMethod { public static void main(String[] args) { printGrade(78.5); } public static void printGrade(double score) { if (score >= 90.0) { System.out.println('A'); } else if (score >= 80.0) { System.out.println('B'); } else if (score >= 70.0) { System.out.println('C'); } else if (score >= 60.0) { System.out.println('D'); } else { System.out.println('F'); } } }

The above example compiles and runs with the following result:

C

Here, the printGrade method is a void type method; it does not return a value.

A call to a void method must be a statement. Therefore, it is called as a statement on the third line of the main method, just like any statement ending with a semicolon.


Passing Parameters by Value

When calling a method, you need to provide arguments. You must provide them in the order specified by the parameter list.

For example, the following method prints a message n times in a row:

TestVoidMethod.java file code:

public static void nPrintln(String message, int n) { for (int i = 0; i < n; i++) { System.out.println(message); } }

Example

The following example demonstrates the effect of passing by value.

The program creates a method that swaps two variables.

TestPassByValue.java file code:

public class TestPassByValue { public static void main(String[] args) { int num1 = 1; int num2 = 2; System.out.println("Before the swap, the value of num1 is:" + num1 + ", and the value of num2 is:" + num2); //Calling the swap method swap(num1, num2); System.out.println("After the swap, the value of num1 is:" + num1 + ", and the value of num2 is:" + num2); } /** Method to swap two variables*/ public static void swap(int n1, int n2) { System.out.println("\tEntering the swap method"); System.out.println("\t\tBefore the swap, the value of n1 is:" + n1 + ", the value of n2:" + n2); //Swapping the values of n1 and n2 int temp = n1; n1 = n2; n2 = temp; System.out.println("\t\tAfter the swap, the value of n1 is" + n1 + ", the value of n2:" + n2); } }

The above example compiles and runs with the following result:

交换前 num1 的值为:1 ,num2 的值为:2
    进入 swap 方法
        交换前 n1 的值为:1,n2 的值:2
        交换后 n1 的值为 2,n2 的值:1
交换后 num1 的值为:1 ,num2 的值为:2

Pass two arguments to call the swap method. Interestingly, after the method is called, the values of the actual arguments do not change.


Method Overloading

The max method used above only works for int type data. But what if you want to get the maximum of two floating-point type data?

The solution is to create another method with the same name but different parameters, as shown in the following code:

public static double max(double num1, double num2) { if (num1 > num2) return num1; else return num2; }

If you pass int type parameters when calling the max method, the max method with int parameters will be called;

If double type parameters are passed, the max method body with double type will be called. This is called method overloading;

That is, two methods of a class have the same name but different parameter lists.

The Java compiler determines which method should be called based on the method signature.

Method overloading can make programs clearer and more readable. Methods that perform closely related tasks should use the same name.

Overloaded methods must have different parameter lists. You cannot overload methods based solely on differences in modifiers or return types.


Variable Scope

The scope of a variable is the part of the program where the variable can be referenced.

Variables defined inside a method are called local variables.

The scope of a local variable starts from its declaration and continues until the end of the block that contains it.

Local variables must be declared before they can be used.

The scope of a method's parameters covers the entire method. Parameters are actually local variables.

Variables declared in the initialization part of a for loop have a scope that spans the entire loop.

However, variables declared in the loop body have a scope from their declaration to the end of the loop body. It contains variable declarations as shown below:

You can declare a local variable with the same name multiple times in different non-nested blocks in a method, but you cannot declare a local variable twice in nested blocks.

Using Command-Line Arguments

Sometimes you want to pass messages to a program when you run it. This is achieved by passing command-line arguments to the main() function.

Command-line arguments are the information that follows the program name when the program is executed.

Example

The following program prints all command-line arguments:

CommandLine.java file code:

public class CommandLine { public static void main(String[] args){ for(int i=0; i<args.length; i++){ System.out.println("args[" + i + "]: " + args[i]); } } }

Run this program as follows:

$ javac CommandLine.java 
$ java CommandLine this is a command line 200 -100
args[0]: this
args[1]: is
args[2]: a
args[3]: command
args[4]: line
args[5]: 200
args[6]: -100

Constructor Methods

A constructor is a special method used to create objects of a class. When an object is created using the new keyword, the constructor is automatically called to initialize the object's properties.

Constructor characteristics:

  • The method name is the same as the class name: The constructor's name must match the class name.
  • No return type: Constructors have no return type; evenvoidvoid cannot be written.
  • Automatically called when creating an object: Every time you usenewnew to create an object, the constructor is automatically called.
  • Can be overloaded: You can define multiple constructors for the same class, but the parameter lists of these constructors must be different (i.e., they constitute an overload).

Whether or not you define a custom constructor, all classes have constructors, because Java automatically provides a default constructor. The access modifier of the default constructor is the same as that of the class (if the class is public, the constructor is also public; if the class is changed to protected, the constructor is also changed to protected).

Once you define your own constructor, the default constructor becomes invalid.

Example

The following is an example of using a constructor:

//A simple constructor class MyClass { int x; //The following is the constructor MyClass(int i ) { x = i; } }

You can call the constructor to initialize an object like this:

ConsDemo.java file code:

public class ConsDemo { public static void main(String[] args) { MyClass t1 = new MyClass( 10 ); MyClass t2 = new MyClass( 20 ); System.out.println(t1.x + " " + t2.x); } }

The running result is as follows:

10 20

For more content, refer to the next chapter:Java Constructors。

Variable Arguments

Starting with JDK 1.5, Java supports passing variable arguments of the same type to a method.

The declaration of a method's variable arguments is as follows:

typeName... parameterName

In the method declaration, add an ellipsis (...) after the specified parameter type.

A method can specify only one variable argument, and it must be the last parameter of the method. Any ordinary parameters must be declared before it.

Example

VarargsDemo.java file code:

public class VarargsDemo { public static void main(String[] args) { //Calling a method with variable arguments printMax(34, 3, 3, 2, 56.5); printMax(new double[]{1, 2, 3}); } public static void printMax( double... numbers) { if (numbers.length == 0) { System.out.println("No argument passed"); return; } double result = numbers[0]; for (int i = 1; i < numbers.length; i++){ if (numbers[i] > result) { result = numbers[i]; } } System.out.println("The max value is " + result); } }

The above example compiles and runs with the following result:

The max value is 56.5
The max value is 3.0

The finalize() Method

The finalize method has been deprecated in Java 9 and will be removed in future Java versions. It is recommended to use try-with-resourcestry-with-resourcesorjava.lang.ref.Cleanerto manage resources.

Java allows defining such a method, which is called before an object is destroyed (collected) by the garbage collector. This method is called finalize(), and it is used to clean up the object being collected.

For example, you can use finalize() to ensure that a file opened by an object is closed.

In the finalize() method, you must specify the operations to be performed when the object is destroyed.

The general format of finalize() is:

protected void finalize() { //The termination code goes here. }

The keyword protected is a qualifier that ensures the finalize() method will not be called by code outside of the class.

Of course, Java's memory reclamation can be done automatically by the JVM. If you want to use it manually, you can use the above method.

Example

FinalizationDemo.java file code:

public class FinalizationDemo { public static void main(String[] args) { Cake c1 = new Cake(1); Cake c2 = new Cake(2); Cake c3 = new Cake(3); c2 = c3 = null; System.gc(); //Invoking the Java garbage collector } } class Cake extends Object { private int id; public Cake(int id) { this.id = id; System.out.println("Cake Object " + id + "is created"); } protected void finalize() throws java.lang.Throwable { super.finalize(); System.out.println("Cake Object " + id + "is disposed"); } }

Running the above code, the output result is as follows:

$ javac FinalizationDemo.java 
$ java FinalizationDemo
Cake Object 1is created
Cake Object 2is created
Cake Object 3is created
Cake Object 3is disposed
Cake Object 2is disposed

Alternative:It is recommended to use the AutoCloseable interface, combined with a try-with-resources statement, to automatically close resources. For example:

try (Resource res = new Resource()) {
    // 使用资源
} catch (Exception e) {
    e.printStackTrace();
}
Other Extensions