Detailed explanation of Java methods

catalogue

01. What is the method?

02. Definition of method

03. Overload of method

04. Variable parameters

05. Recursion

01. What is the method?

  • A Java method is a collection of statements that together perform a function.
    • Method is an ordered combination of steps to solve a class of problems
    • Method is contained in a class or object
    • Methods are created in the program and referenced elsewhere
  • Principle of design method: the original intention of the method is function block, that is, a method only completes one function, which is conducive to our later expansion
public class Demo01 {
    //main method 
    public static void main(String[] args) {
//        int i = add(1, 2);
//        System.out.println(i);
        test();
    }

    //addition
    public static int add(int a, int b) {
        return a + b;
    }

    public static void test() {
        for (int i = 1; i <= 10; i++) {
            for (int j = 10; j >= i; j--) {
                System.out.print(" ");
            }
            for (int j = 1; j <= i; j++) {
                System.out.print("*");
            }
            for (int j = 2; j <= i; j++) {
                System.out.print("*");
            }
            System.out.println(" ");
        }
    }
}

02. Definition of method

  • Java methods are similar to functions in other languages. They are code fragments used to complete specific functions. Generally, defining a method includes the following syntax:
  • Method contains a method header and a method body. Here are all parts of a method:
    • Modifier: modifier, which is optional and tells the compiler how to call the method. Defines the access type of the method.
    • Return value type: the method may return a value. returnValueType is the data type of the return value of the method. Some methods perform the required operation but do not return a value. In this case, returnValueType is the keyword void.
    • Method name: the actual name of the method. The method name and parameter table together constitute the method signature.
    • Parameter type: the parameter is like a placeholder. When a method is called, a value is passed to the parameter. This value is called an argument or variable. Parameter list refers to the parameter type, order and number of parameters of a method. Parameters are optional, and methods can contain no parameters.
      • Formal parameter: used to receive external input data when the method is called.
      • Argument: the data actually passed to the method when the method is called.
    • Method body: the method body contains specific statements that define the function of the method.
  • Calling method: object name Method name (argument list)
  • Java supports two methods of calling methods, which are selected according to the return value of the method
  • If the return value of the method is void, the method call must be a statement
  • When a method returns a value, the method call is usually treated as a value. For example:
int larger = max(30,40);
Modifier return value type method name (parameter type parameter name){
    ...
    Method body
    ...
    return Return value;

}
//Method call
public class Demo02 {
    public static void main(String[] args) {
        int max = max(10, 10);
        System.out.println(max);
    }

    //Specific size
    public static int max(int a, int b) {
        int result = 0;

        if (a == b) {
            System.out.println("a==b");
            return 0;
        } else if (b > a) {
            result = b;
        } else if (b < a) {
            result = a;
        }
        return result;
    }
}

03. Overload of method

  • Overloading is a function with the same function name but different formal parameters in a class.
  • Overload rule for method:
    • Method names must be the same.
    • The parameter list must be different (different number, different type, different parameter arrangement order, etc.).
    • Different return types of methods are not enough to be overloaded.
    • Simply having different return types is not enough to be called method overloading.
  • Implementation theory:
    • If the method names are the same, the compiler will match them one by one according to the number of parameters and parameter types of the calling method to select the corresponding method. If the matching fails, the compiler will report an error.
//Method overload
public class Demo03 {
    public static void main(String[] args) {
        add(10, 20);
        add(1, 2, 3);
        add(1, 2, 3.0);
    }

    public static int add(int a, int b) {
        int result = 0;
        if (a == b) {
            System.out.println("a and b equal");
            return 0;
        } else if (a > b) {
            result = a;
        } else if (a < b) {
            result = b;
        }
        return result;
    }

    public static int add(int a, int b, int c) {
        int result = 0;
        if (a == b) {
            System.out.println("a and b equal");
            return 0;
        } else if (a > b) {
            result = a;
        } else if (a < b) {
            result = b;
        }
        return result;
    }

    public static int add(int a, int b, double c) {
        int result = 0;
        if (a == b) {
            System.out.println("a and b equal");
            return 0;
        } else if (a > b) {
            result = a;
        } else if (a < b) {
            result = b;
        }
        return result;
    }
}

04. Variable parameters

  • JDK1. Starting from 5, Java supports passing variable parameters of the same type to a method.
  • In the method declaration, add an ellipsis (...) after specifying the parameter type.
  • Only one variable parameter can be specified in a method. It must be the last parameter of the method. Any ordinary parameter must be declared before it.
//Variable parameters
public class Demo04 {
    public static void main(String[] args) {
        Demo04 demo04 = new Demo04();
        demo04.printMax(4, 7, 8, 9);
        demo04.printMax(4.6,3.6,7.9);
    }

    public void printMax(double... number) {
        if (number.length == 0) {
            System.out.println("Not Message");
        }
        double result = 0;
        for (int i = 0; i < number.length; i++) {
            if (number[i] > result) {
                result = number[i];
            }
        }
        System.out.println("The Max Value is:" + result);
    }
}

05. Recursion

  • Method A calls method B, which is easy for us to understand!
  • Recursion is: method A calls method A and calls itself.
  • Using recursion, we can solve some complex problems with simple programs. It usually transforms a large and complex problem layer by layer into a smaller problem similar to the original problem to solve. The recursive strategy only needs a small number of programs to describe the multiple repeated calculations required in the problem-solving process, which greatly reduces the amount of code of the program. The ability of recursion is to define a wireless set of objects with limited statements.
  • The recursive structure consists of two parts:
    • Recursive header: when not to call its own method. If there is no head, it will fall into a dead cycle.
    • Recursive tail: when to call its own method.
public class Demo06 {
    //5! 5*4*3*2*1
    public static void main(String[] args) {
        System.out.println(f(10));
    }

    public static int f(int n) {
        if (n == 1) {
            return 1;
        } else {
            return n * f(n - 1);
        }
    }
}
  • Exercise (write a simple calculator using the Scanner object)
public class Demo07 {
    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        char over = 'y';

        do {
            if (over == 'y') {
                System.out.println("Please enter the first number!");
                int num01 = scanner.nextInt();
                System.out.println("Please enter the number to be calculated!");
                int num02 = scanner.nextInt();

                System.out.println("Please enter the method to calculate(+ - * /)");
                char calculation = scanner.next().charAt(0);

                switch (calculation) {
                    case '+':
                        System.out.println("The sum obtained is:" + (num01 + num02));
                        break;
                    case '-':
                        System.out.println("The calculated difference is:" + (num01 - num02));
                        break;
                    case '*':
                        System.out.println("The product obtained is:" + (num01 * num02));
                        break;
                    case '/':
                        System.out.println("The division obtained is:" + (num01 / num02));
                        break;
                    default:
                        System.out.println("Input error, please check the input!");
                        break;
                }
                System.out.println("input y Continue, enter any character to end!");
                over = scanner.next().charAt(0);
            } else {
                break;
            }
        } while (true);
    }
}

Keywords: Java Back-end

Added by shorty3 on Wed, 05 Jan 2022 07:42:45 +0200