Java methods


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

println() is a method (Method), and System is the system class (Class), and out is the standard output object (Object). The usage of this sentence is to call the method println() in the standard output object out in the system class System.

So what is the method?

Java methods are a collection of statements that together perform a function.

  • A method is an ordered combination of steps to solve a type of problem

  • Methods are contained in a class or object

  • Methods are created in the program and referenced elsewhere


#Definition of method

Generally, defining a method contains the following Syntax:

修饰符 返回值类型 方法名 (参数类型 参数名){
    ...
    方法体
    ...
    return 返回值;
}

The method contains a method header and a method body. Here are all the parts of a method:

  • Modifiers: The modifier, which is optional, tells the compiler how to call the method. Defines the access type for this method.

  • Return value type: Methods may return values. returnValueType is the data type of the method return value. Some methods perform the required operation but do not return a value. In this case, returnValueType is the keyword void.

  • Method name: is the actual name of the method. The method name and parameter list together form the method signature.

  • Parameter type: The parameter is like a placeholder. When the method is called, values ​​are passed to the parameters. This value is called an actual parameter or variable. The parameter list refers to the parameter type, order and number of parameters of the method. Parameters are optional and methods can contain no parameters.

  • Method body: The method body contains specific statements that define the function of the method.

12-130Q1220955916.jpg

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 refer to procedures and functions. A method that returns a non-void return value is called a function; a method that returns a void return value is called a procedure.

Example

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

/** 返回两个整型变量数据的较大值 */
public static int max(int num1, int num2) {
   int result;
   if (num1 > num2)
      result = num1;
   else
      result = num2;

   return result; 
}

Method call

Java supports two ways to call methods, choose according to whether the method returns a value.

When a program calls a method, control of the program is given to the called method. Control is returned to the program when the return statement of the called method is executed or the method body closing bracket is reached.

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

int larger = max(30, 40);

If the method return value is 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 Java!");

Example

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

public class TestMax {
   /** 主方法 */
   public static void main(String[] args) {
      int i = 5;
      int j = 2;
      int k = max(i, j);
      System.out.println("The maximum between " + i +
                    " and " + j + " is " + k);
   }

   /** 返回两个整数变量较大的值 */
   public static int max(int num1, int num2) {
      int result;
      if (num1 > num2)
         result = num1;
      else
         result = num2;

      return result; 
   }
}

The compilation and running results of the above example are as follows:

The maximum between 5 and 2 is 5

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

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


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

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 compilation and running results of the above example are as follows:

C

The printGrade method here is a void type method and 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 that ends with a semicolon.


Passing parameters by value

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

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

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.

This program creates a method that is used to exchange two variables.

public class TestPassByValue {

   public static void main(String[] args) {
      int num1 = 1;
      int num2 = 2;

      System.out.println("Before swap method, num1 is " +
                          num1 + " and num2 is " + num2);

      // 调用swap方法
      swap(num1, num2);
      System.out.println("After swap method, num1 is " +
                         num1 + " and num2 is " + num2);
   }
   /** 交换两个变量的方法 */
   public static void swap(int n1, int n2) {
      System.out.println("\tInside the swap method");
      System.out.println("\t\tBefore swapping n1 is " + n1
                           + " n2 is " + n2);
      // 交换 n1 与 n2的值
      int temp = n1;
      n1 = n2;
      n2 = temp;

      System.out.println("\t\tAfter swapping n1 is " + n1
                           + " n2 is " + n2);
   }
}

The compilation and running results of the above example are as follows:

Before swap method, num1 is 1 and num2 is 2
        Inside the swap method
                Before swapping n1 is 1 n2 is 2
                After swapping n1 is 2 n2 is 1
After swap method, num1 is 1 and num2 is 2

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


Overloading of methods

The max method used above is only applicable to int type data. But what if you want to get the maximum value of two floating point types of 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 you call the max method, then int type The max method of the parameter will be called;

If a double parameter is passed, the max method body of the double type will be called, which is called method overloading;

It means a class The two methods 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 the program clearer and easier to read. Methods that perform closely related tasks should use the same name.

Overloaded methods must have different parameter lists. You can't overload methods based solely on 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 within a method are called local variables.

The scope of a local variable starts from the declaration and ends at the end of the block that contains it.

Local variables must be declared before they can be used.

The parameter range of the method covers the entire method. The parameter is actually a local variable.

The variables declared in the initialization part of the for loop have their scope within the entire loop.

But the scope of application of the variable declared in the loop body is from its declaration to the end of the loop body. It contains variable declarations as shown below:

12-130Q1221013F0.jpg

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

Use of command line parameters

Sometimes you want to pass a message to a program before running it. This is accomplished by passing command line arguments to the main() function.

Command line parameters are the information immediately following the program name when executing the program.

Example

The following program prints all command line parameters:

public class CommandLine {

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

As shown below, run this program:

java CommandLine this is a command line 200 -100

The running results are as follows:

args[0]: this
args[1]: is
args[2]: a
args[3]: command
args[4]: line
args[5]: 200
args[6]: -100

Constructor method

When an object is created, the constructor method is used to initialize the object. The constructor has the same name as the class it is in, but the constructor has no return value.

Constructors are usually used to assign initial values ​​to instance variables of a class, or to perform other necessary steps to create a complete object.

Whether you customize the constructor or not, all classes have constructors, because Java automatically provides a default constructor, which initializes all members to 0.

Once you define your own constructor, the default constructor will become invalid.

Example

The following is an example of using the constructor method:

// 一个简单的构造函数
class MyClass {
   int x;
   
   // 以下是构造函数
   MyClass() {
      x = 10;
   }
}

You can call the constructor method to initialize an object like the following:

public class ConsDemo {

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

Mostly Sometimes a constructor with parameters is needed.

Example

The following is an example of using the constructor method:

// 一个简单的构造函数
class MyClass {
   int x;
   
   // 以下是构造函数
   MyClass(int i ) {
      x = i;
   }
}

You can call the constructor method to initialize an object like the following:

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);
   }
}

Run The results are as follows:

10 20

Variable parameters

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

The declaration of the variable parameters of the method is as follows:

typeName... parameterName

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

Only one variable parameter can be specified in a method, and it must be the last parameter of the method. Any ordinary parameters must be declared before it.

Example

public class VarargsDemo {

   public static void main(String args[]) {
      // 调用可变参数的方法
	  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 compilation and running results of the above example are as follows:

The max value is 56.5
The max value is 3.0

finalize() method

Java allows the definition of such a method, which is Called before the object is destructed (recycled) by the garbage collector, this method is called finalize(), which is used to clear the recycled object.

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 keyword protected is a qualifier, which ensures that the finalize() method will not be called by code outside the class.

Of course, Java's memory recycling can be automatically completed by the JVM. If you use it manually, you can use the method above.

Example

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(); //调用Java垃圾收集器
    }  
}  
  
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");  
    }  
}

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

C:>java FinalizationDemo  
Cake Object 1is created  
Cake Object 2is created  
Cake Object 3is created  
Cake Object 3is disposed  
Cake Object 2is disposed