Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Java method


May 10, 2021 Java


Table of contents


Java method

We used System.out.println() a lot in the previous chapters, so what is it?

println() is a method, while System is a system class and out is a standard output object (Object). This sentence is used to call the method println() in the standard output object out in the system class System.

So what is the method?

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

  • Methods are an ordered combination of steps to solve a class of problems

  • Methods are contained in classes or objects

  • Methods are created in the program and referenced elsewhere


The definition of the method

In general, defining a method contains the following syntax:

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

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

  • Modifier: The modifier, which is optional, tells the compiler how to call the method. The access type of the method is defined.

  • Return value type: The method may return a value. R eturnValueType is the data type of the method's return value. S ome methods perform the required operations, but do not return a value. In this case, returnValueType is the keyword void.

  • Method name: Is the actual name of the method. Method names and parameter tables together make up the method signature.

  • Argument type: The argument looks like a placeholder. W hen the method is called, the value is passed to the argument. T his value is called an argument or variable. A list of parameters is the type, order, and number of parameters of a method. Arguments are optional, and methods can contain no parameters.

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

Java method

Such as:

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

Arguments can have more than one:

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

Note: In some other languages, methods refer to procedures and functions. A method for returning a value for a nonvoid type is called a function;

Instance

The following method contains two parameters, num1 and num2, which return the maximum values for both 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, depending on whether the method returns a value.

When a program calls a method, control of the program is handed over to the called method. Return control to the program when the return statement of the called method executes or reaches the closed parenthesis of the method body.

When a method returns a value, a method call is usually considered a value. For example:

int larger = max(3040);

If the method returns a value ofvoid, the method call must be a statement. F or example, the method println returns void. The following call is a statement:

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

Example

The following example shows 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 above examples compile and run 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, except that the main method is no different from other methods.

The head of the main method is unchanged, as shown in the example, with modifier public and static, returning the void type value, the method name is main, and also with a String type parameter. String indicates that the argument is an array of strings.


Void keyword

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

The following example declares a method called printGrade and uses it to print a 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 above examples compile and run as follows:

C

Here the printGrade method is a void type method that does not return a value.

The call to avoid method must be a statement. T herefore, it is called as a statement on the third line of the main method. Just like any statement that ends with a sign.


Pass parameters by value

When you call a method, you need to provide parameters, which you must provide in the order specified in the list of parameters.

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

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 exchanges 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 above examples compile and run 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 value of the real parameter does not change after the method is called.


The overload of the method

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

The workaround 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 call the max method to pass an int-type argument, the max method of the int-type argument is called;

If the doble parameter is passed, the max experience of the double type is called, which is called method overloading;

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

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

Method overloading makes 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 just based on modifiers or different types of returns.


Variable scope

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

Variables defined within a method are called local variables.

The scope of a local variable starts with the declaration and ends with the block containing it.

Local variables must be declared before they can be used.

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

The initialization portion of the for loop declares a variable whose scope of action is throughout the loop.

However, the variable declared in the loop body is suitable from its declaration to the end of the loop body. It contains variable declarations such as the following:

Java method

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

The use of command-line parameters

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

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

Instance

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

Run the program as follows:

java CommandLine this is a command line 200 -100

The 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


The construction method

When an object is created, the construction method is used to initialize the object. The construction method has the same name as the class it is in, but the construction method does not return a value.

You typically use the construction method to give an initial value to an instance variable of a class, or to perform other necessary steps to create a complete object.

Whether you customize the construction method or not, all classes have a construction method because Java automatically provides a default construction method that initializes all members to 0.

Once you have defined your own construction method, the default construction method will invalidate.

Instance

Here's an example of using a construction method:

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

You can call the construction method to initialize an object like this:

public class ConsDemo {

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

Most of the time, a construction method with parameters is required.

Instance

Here's an example of using a construction method:

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

You can call the construction method to initialize an object like this:

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 results are as follows:

10 20

Variable parameters

Starting with 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 oscillos mark (...) after specifying the parameter type.

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

Instance

public class VarargsDemo {

   public static void main(String args[]) {
      // 调用可变参数的方法
	  printMax(3433256.5);
      printMax(new double[]{123});
   }

   public static void printMaxdouble... 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 examples compile and run as follows:

The max value is 56.5
The max value is 3.0


Finalize() method

Java allows you to define a method that is called before an object is destructed (recycled) by a garbage collector, called finalize ( ) , which is used to clean up the recycled object.

For example, you can use findize() to make sure that an object-opened file is closed.

In the finalize() method, you must specify what to do when the object is destroyed.

The general format of finalize() is:

protected void finalize()
{
   // 在这里终结代码
}

The keyword protected is a qualifier that ensures that the finalize() method is not called by code other than that class.

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

Instance

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 and the output is as follows:

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