[dark horse programmer Java notes] method

catalogue

1. Method overview

2. Definition and invocation of simple methods

3. Definition and invocation of methods with parameters

4. Definition and call of method with return value

5. Method overloading

6. Parameter passing of method

1. Method overview

The method is to organize the code blocks with independent functions into a whole and make them a code set with special functions.

Methods must be created before they can be used. This process is called method definition. (methods cannot be nested)

Methods do not run directly after they are created. They need to be used manually before they can be executed. This process is called method call. (the method must first be defined, then called, otherwise the program will be wrong).

Method definition general format:

public static return value type method name (parameter){

Method body;

return data;

                }

2. Definition and invocation of simple methods

Definition:

public static void Method name(){   // void means no return value, and return can be omitted; You can also write return separately without data
    // Method body
}

Calling: method name ();

public class Method_2 {
    public static void main(String[] args) {
        // Call method
        isEvenNumber(); // true

        // 4. invoke a well-defined method in the main method.
        getMax();   // 20
    }

    // Requirement: define a method, define a variable in the method, and judge whether the data is even
    public static void isEvenNumber(){
        // Define variables
        int number = 10;

        // Judge whether the data is even
        if (number % 2 == 0){
            System.out.println(true);
        }
        else
            System.out.println(false);
    }

    /*
   Requirements: design a method to print the larger of the two numbers

   Idea:
       1. Define a method to print the larger of two numbers, such as getMax()
       2. Method to hold two numbers
       3. Branch statements are used to deal with the size relationship between two numbers in two cases
       4. Invoking a well-defined method in the main method
   */
    // 1. Define a method to print the larger of the two numbers, such as getMax()
    public static void getMax(){
        // 2. Two variables are defined in the method to save two numbers
        int a = 10;
        int b = 20;

        // 3. Use branch statements to deal with the size relationship between two numbers in two cases
        if (a > b){
            System.out.println(a);
        }
        else
            System.out.println(b);
    }
}

3. Definition and invocation of methods with parameters

Formal parameter: parameter in method definition -- equivalent to variable definition format, such as int number

Arguments: parameters in method calls -- equivalent to using variables or constants, such as 10 number

Definition: public static void method name (data type variable name) {...}

                         public static void isEvenNumber(int number){......}

                         public static void isEvenNumber(int number1, int number2){......}

When defining a method, the data type and variable name in the parameter cannot be missing. If any program is missing, an error will be reported; Multiple parameters are separated by commas.

Call: method name (variable name / constant value);

                        isEvenNumber(5);

                        getMax(1, 2);

When calling a method, the number and type of parameters must match the settings in the method definition, otherwise the program will report an error.

public class Method_3 {
    public static void main(String[] args) {
        // Call of constant value
        isEvenNumber(5);    // false
        // Call of variable
        int number = 10;
        isEvenNumber(number);   // true

        getMax(20,30);  // 30
    }

    // Requirement: define a method that receives a parameter to determine whether the data is even
    public static void isEvenNumber(int number){
        if (number % 2 == 0){
            System.out.println(true);
        }
        else {
            System.out.println(false);
        }
    }

    /*
        Requirements: design a method to print the larger of the two numbers, and the data comes from the method parameters

        Idea:
            1. Define a method to print the larger of two numbers, such as getMax()
            2. Define two parameters for the method to receive two numbers
            3. Branch statements are used to deal with the size relationship between two numbers in two cases
            4. Invoking a well-defined method in the main method
    */
    public static void getMax(int a, int b){
        if (a > b){
            System.out.println(a);
        }
        else
            System.out.println(b);
    }
}

4. Definition and call of method with return value

Definition:

public static Data type method name(parameter){
    ......
    return data;
}

public static boolean isEvenNumber(int number){
    ......
    return true;
}

When defining a method, the return value after return should match the data type on the method definition, otherwise the program will report an error.

Call: method name (parameter);

                        isEvenNumber(5);

Data type variable name = method name (parameter);

                        boolean flag = isEvenNumber(5);

The return value of a method is usually received using a variable, otherwise the return value will be meaningless.

public class Method_4 {
    public static void main(String[] args) {
        boolean flag = _isEvenNumber_(11);
        System.out.println(flag);   // false

        System.out.println(_getMax_(30,40));    // 40
    }

    // Requirement: define a method that receives a parameter, determines whether the data is even, and returns true and false values
    public static boolean _isEvenNumber_(int number){
        if (number % 2 == 0){
            return true;
        }
        else {
            return false;
        }
    }

    public static int _getMax_(int a, int b){
        if (a > b){
            return a;
        }
        else {
            return b;
        }
    }
}

5. Method overloading

Multiple methods defined in the same class constitute overloads if they meet the following conditions:

1) multiple methods in the same class

2) multiple methods have the same method name

3) the parameters of multiple methods are different - different types or quantities

Features:

Overloading only corresponds to the definition of the method and has nothing to do with the method call. The call method refers to the standard format.

Overloading only identifies the names and parameters of methods in the same class, regardless of the return value. In other words, the return value cannot be used to determine whether two methods constitute overloads with each other.

public class Method_5 {
    public static void main(String[] args) {
        System.out.println(sum(1,2));
        System.out.println(sum(1.0,2.0));
        System.out.println(sum(1,2,3));

        System.out.println("\n");

        System.out.println(compare(10,20));
        System.out.println(compare((byte)10,(byte)20));
        System.out.println(compare((short)10,(short)20));
        System.out.println(compare(10L,20L));
    }

    // Requirements: simple summation
    public static int sum(int a, int b){
        return a + b;
    }
    public static double sum(double a, double b){
        return a + b;
    }
    public static int sum(int a, int b, int c){
        return a + b + c;
    }

    /*
        Requirements: use the idea of method overloading to design a method to compare whether two integers are equal, which is compatible with all integer types (byte, short, int, long)
    */
    public static boolean compare(int a, int b){
        System.out.println("int");
        return a == b;
    }
    public static boolean compare(byte a, byte b){
        System.out.println("byte");
        return a == b;
    }
    public static boolean compare(short a, short b){
        System.out.println("short");
        return a == b;
    }
    public static boolean compare(long a, long b){
        System.out.println("long");
        return a == b;
    }
}

// Operation results
/*
3
3.0
6


int
false
byte
false
short
false
long
false
*/

6. Parameter passing of method

For parameters of basic data type, the change of formal parameter does not affect the value of actual parameter

/*
For parameters of basic data type, the change of formal parameter does not affect the value of actual parameter
*/
public class ArgsDemo01 {
    public static void main(String[] args) {
        int number = 100;
        System.out.println("call change Before method:" + number);
        change(number);
        System.out.println("call change After method:" + number);
    }
    public static void change(int number){
        number = 200;
    }
}

// Operation results
/*
Before calling the change method: 100
 After calling the change method: 100
*/

For parameters that reference data types, the change of formal parameters will affect the value of actual parameters

/*
For parameters that reference data types, the change of formal parameters will affect the value of actual parameters
*/
public class ArgsDemo02 {
    public static void main(String[] args) {
        int[] arr = {10, 20, 30};
        System.out.println("call change Before method:" + arr[1]);
        change(arr);
        System.out.println("call change After method:" + arr[1]);
    }
    public static void change(int[] arr){
        arr[1] = 200;
    }
}

// Operation results
/*
Before calling the change method: 20
 After calling the change method: 200
*/

public class Method_6 {
    public static void main(String[] args) {
        int[] arr = {11, 22, 33, 44, 55};
        printArray(arr);
        System.out.println(getMax(arr));
    }

    /*
        Array traversal
        Requirements: design a method to traverse the array. The traversal result is required to be on one line. Such as [11, 22, 33, 44, 55]
    */
    public static void printArray(int[] arr){
        System.out.print("[");
        for(int i = 0; i < arr.length; i++){
            if (i == arr.length - 1){
                System.out.print(arr[i]);
            }
            else {
                System.out.print(arr[i] + ", ");
            }
        }
        System.out.println("]");
    }

    /*
        Array maximum
        Requirements: design a method to obtain the maximum value of elements in the array, call the method and output the result
    */
    public static int getMax(int[] arr){
        int max = arr[0];
        for(int j = 1; j < arr.length; j++){
            if(arr[j] > max){
                max = arr[j];
            }
        }
        return max;
    }
}

Keywords: Java

Added by khf79 on Tue, 15 Feb 2022 04:04:03 +0200