Java-method usage

Table of contents

1. The concept and use of the method

      1.1 The meaning of the method

      1.2 Definition of method

      1.3 Execution process of method call

      1.4 The relationship between actual parameters and formal parameters

      1.5 Methods with no return value

2. Method overloading

      2.1 The meaning of method overloading

      2.3 Method signature

3. Recursion

3.1 The concept of recursion

3.2 Recursive execution process

3.3 Recursion exercises


1. The concept and use of the method

      1.1 The meaning of the method

           A method is a piece of code. Similar to a function in C language.

           The role of the method:

                    1. Be able to organize code in a modular manner (when the code size is relatively complex).
                    2. The code is reused, and one code can be used in multiple locations.
                    3. Make the code easier to understand and easier.
                    4. Directly call the existing method without typing the same code repeatedly

      1.2 Definition of method

            Grammar format:

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


           example

public static  boolean IsYear(int year){
    if((0 == year % 4 && 0 != year % 100) || 0 == year % 400){
        return true;
    }else{
        return false;
    }
}

        Note: modifier: use public static fixed collocation directly at this stage; return value type: if the method has a return value, the return value type must be consistent with the returned entity type, if there is no return value, it must be written as void; method name: use small Camel case naming; parameter list: if the method has no parameters, write nothing in (), if there are parameters, you need to specify the parameter type, and use commas to separate multiple parameters; in java, the method must be written in the class, the method Nested definitions cannot be nested, and there is no method declaration, which means that no method declaration is required.

      1.3 Execution process of method call

        Calling process: call method ---> pass parameters ---> find the method address ---> execute the method body of the called method ---> the called method ends and returns ---> return to the calling method and continue down implement.

example

public static int add1(int x, int y){
//x, y are formal parameters, save the passed data, and the parameters in the main function do not change
    return x + y;
}
public static void main(String[] args) {
    int a = 10;
    int b = 20;
    int ret = add1(a, b);
    System.out.println("ret = " + ret);
    right = add1(30, 50);
    System.out.println("ret = " + ret);
}

         Note: When a method is defined, the code of the method will not be executed, it will only be executed when it is called; a method can be called multiple times.

      1.4 The relationship between actual parameters and formal parameters

        The formal parameter of the method is equivalent to the independent variable in the mathematical function. The name of the formal parameter can be chosen at will, and has no effect on the method. The formal parameter is just a variable that the method needs to use when it is defined, and is used to save the method passed when calling. value. In Java, the value of the actual parameter is always copied to the form, and the formal parameter and the actual parameter are essentially two entities .

example

public static void main(String[] args) {
    int a = 10;
    int b = 20;
    swap(a, b);
    System.out.println("main: a = " + a + " b = " + b);
}
// swap values
public static void swap(int x, int y) {
    int tmp = x;
    x = y;
    y = tmp;
    System.out.println("swap: x = " + x + " y = " + y);
}

         After the exchange of the swap function, the values ​​of the formal parameters x and y have changed, but in the main method, a and b are still the values ​​before the exchange, that is, the exchange is not successful.

        Reason analysis: the actual parameters a and b are two variables in the main method, and their space is in the stack (a special memory space) of the main method, while the formal parameters x and y are two variables in the swap method, x and The space of y is in the stack when the swap method is running, so the actual parameters a and b and the formal parameters x and y are two unrelated variables. When the swap method is called, only the values ​​in the actual parameters a and b are copied A copy is passed to the formal parameters x and y, so the operation on the formal parameters x and y will not have any impact on the actual parameters a and b. For the basic type, the formal parameter is equivalent to a copy of the actual parameter. That is, passing by value call .

        Solution: pass reference type parameters (such as arrays to solve this problem)

        example

public static void main(String[] args) {
    int[] arr = {10, 20};
    swap(arr);
    System.out.println("arr[0] = " + arr[0] + " arr[1] = " + arr[1]);
}
public static void swap(int[] arr) {
    int tmp = arr[0];
    arr[0] = arr[1];
    arr[1] = tmp;
}

      1.5 Methods with no return value

        The return value of the method is optional, if not, the return value type must be written as void.

public static void main(String[] args) {
    int a = 10;
    int b = 20;
    print(a, b);
}
public static void print(int x, int y) {
    System.out.println("x = " + x + " y = " + y);
}

2. Method overloading

      2.1 The meaning of method overloading

        Overloading is a situation where functions or methods have the same name but different parameter lists. Such functions or methods with the same name but different parameters are called overloaded functions or overloaded methods.

        2.2 The role of method overloading

        Method overloading eliminates the need to write multiple functions for different parameter types or number of parameters. Multiple functions use the same name, but the parameter list, that is, the number of parameters or (and) data types can be different. When calling, although the method name is the same, the corresponding function can be automatically called according to the parameter list. Note: For overloaded functions, the method names must be the same; the parameter lists must be different (the number of parameters is different, the types of parameters are different, and the order of types is different), regardless of whether the return value type is the same; when the compiler compiles the code, it will The actual parameter type is deduced, and which method to call is determined according to the deduction result .

example

public static void main(String[] args) {
    int a = 10;
    int b = 20;
    double c = 10;
    double d = 20;
    int ret = add(a, b);
    System.out.println(ret);
    System.out.println(add(c,d));
}
public static int add(int x, int y) {
    return x + y;
}
public static double add(double x, double y) {
    return x + y;
}

      2.3 Method signature

        Two identifiers with the same name cannot be defined in the same scope. For example: two variables with the same name cannot be defined in a method, so why can a method with the same method name be defined in a class? The method signature is: the final name of the method after being compiled and modified by the compiler. Specific method: method full path name + parameter list + return value type to form the complete name of the method .

        Some special symbols in method signatures

Special characters type of data
V void
Z boolean
B byte
C char
S short
I int
J long
F float
D double
[ Array (beginning with [, with other special characters, expresses an array of the corresponding data type, several [ expresses a several-dimensional array)
L Reference type, starting with L and ending with ;, the middle is the full class name of the reference type

3. Recursion

3.1 The concept of recursion

        Recursion is when a method calls itself during execution. Recursion is equivalent to "mathematical induction" in mathematics, there is an initial condition, and then there is a recursive formula.
        Such as: ask for N!

         Initial condition: when N=1, N! =1, the start condition is equivalent to the recursion end condition.

        Recursive formula: find N! , It’s not easy to ask directly, you can N! =N*(N-1)!
        Necessary conditions for recursion:
                1. Divide the original problem into its sub-problems. Note: the sub-problems must have the same solution as the original problem.
                2. Recursive exit

Example Find the factorial of N

public static void main(String[] args) {
        int n = 5;
        int ret = factor(n);
        System.out.println("ret = " + ret);
}
public static int factor(int n) {
        if (n == 1) {
        return 1;
        }

        return n * factor(n - 1)

}

3.2 Recursive execution process

        The execution process of a recursive program is not easy to understand. To understand recursion clearly, you must first understand the "execution process of the method", especially "after the method execution ends, return to the calling location and continue to execute".
        

         Example Find N recursively!
 

public static void main(String[] args) { int n = 5; int ret = factor(n); System.out.println("ret = " + ret); } public static int factor(int n) {         System. out.println("Function start, n = " + n);         if (n == 1) {                 System.out.println("Function end, n = 1 ret = 1");                 return 1;         }









        int ret = n * factor(n - 1);
        System.out.println("Function end, n = " + n + " ret = " + ret);
        return ret;

}

3.3 Recursion exercises

        Example 1 Print each digit of the number in order, such as the number 1234, print 1 2 3 4

public static void func(int n){
    if(n/10==0){
        System.out.println(n);
    }
    else {
        func(n/10);
        System.out.println(n%10);
    }
}
public static void main(String[] args) {
    int a=1234;
    func(a);
}

         Example 2 Recursively find 1+2+...+10

public static int func1(int n){
    if(n==1)
        return 1;
    else
        return n+func1(n-1);
}
public static void main(String[] args) {
    int a=10;
    System.out.println(func1(a));
}

        Example 3 Write a recursive method, input a non-negative integer, and return the sum of its numbers. For example, input 1729, it should return 1+7+2+9, and its sum is 19.

public static int func2(int n){
    if(n/10==0){
        return n;
    }
    else {
        return n%10+func2(n/10);
    }
}
public static void main(String[] args) {
    int a=1729;
    System.out.println(func2(a));
}

        When using the recursive method, the execution speed of the program may be very slow due to a large number of repeated operations. It is necessary to judge whether to use the recursive or circular method according to the specific situation .

 

 

Guess you like

Origin blog.csdn.net/qq_64668629/article/details/131968144