[JavaSE] The use of Java methods

【Goal of this episode】

1. Master the definition and use of methods

2. Master the method of passing parameters

3. Master method overloading

4. Master recursion

Directory

1. Method concept and use

1.1 What is a method (method)

1.2 Method Definition

1.3 Execution process of method call

1.4 The relationship between actual parameters and formal parameters

2. Method overloading

2.1 Why method overloading is needed

2.2 Method overloading concept

3. Recursion

3.1 Stories in life

3.2 The concept of recursion

3.3 Analysis of recursive execution process

3.4 Recursion exercise

1. Method concept and use

1.1 What is a method (method)

A method is a code fragment. Similar to “function” in C language. The meaning of the method (don’t memorize it, focus on understanding):

1. It is possible to organize the code modularly (when the code size is more complex).

2. To make the code reused, a code can be used in multiple places.

3. Make the code easier to understand and easier.

4. Directly call existing method development, without having to reinvent the wheel.

1.2 Method Definition

method syntax format

For example: implement a method to add two integers

public static int add(int x,int y){
        return x + y;
}

Write a method to detect whether a year is a leap year

public static boolean isLeapYear(int year) {
        if ((year % 3 == 0 & amp; & amp; year % 100 != 0) || (year % 400 == 0)) {
            return true;
        }
        return false;
}

[Notes]

1. Modifier: directly use public static fixed collocation at this stage

2. 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

3. Method name: Named with a small camel case

4. 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

5. Method body: the statement to be executed inside the method

6. In java, the method must be written in the class

7. In java, methods cannot be defined nested

8. In java, there is no method declaration

1.3 Execution process of method call

【Method call 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 to execute

【Precautions】

  • 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

Code Example: Calculates 1! + 2! + 3! + 4! + 5!

public class Test {
    //Find the factorial of n
    public static int fac(int n) {
        int ret = 1;
        for (int i = 1; i <= n; i ++ ) {
            ret *= i;
        }
        return ret;
    }
    //Find the factorial sum
    public static int facSum(int k){
        int sum = 0;
        for (int i = 1; i <= k; i ++ ) {
            sum + =fac(i);
        }
        return sum;
    }
    public static void main(String[] args) {
        int ret = facSum(5);
        System.out.println(ret);
    }
}

1.4 Relationship between actual parameters and formal parameters

The formal parameter of the method is equivalent to the argument in the mathematical function, for example: the formula of 1 + 2 + 3 + … + n is sum(n) =

The formal parameter of the method in Java is equivalent to the argument n in the sum function, which is used to receive the value passed by the sum function when it is called. The name of the formal parameter can be chosen arbitrarily, and it has no effect on the method. The formal parameter is just a variable that the method needs to use when defining it, and is used to save the value passed when the method is called.

Another example:

Note: In Java, the value of the actual parameter is always copied to the formal parameter, and the formal parameter and the actual parameter are essentially two entities

Code Example: Swap two integer variables

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

It can be seen that 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.

【Cause 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, the space of x and y In the stack when the swap method is running, therefore: 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 actual parameters a and b A copy of the value is passed to the formal parameters x and y, so operations on the formal parameters x and y will not have any impact on the actual parameters a and b.

Note: For the basic type, the formal parameter is equivalent to a copy of the actual parameter. That is, call by value

[Solution]: Pass reference type parameters (such as arrays to solve this problem)

public class TestMethod {
    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;
    }
}
// operation result
arr[0] = 20 arr[1] = 10

2. Method overloading

2.1 Why do you need method overloading

Still taking the previous addition function as an example:

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

This string of code can run normally, but there is a limitation, that is, when the actual parameter is not int type data, the program will go wrong:

Since the parameter types do not match, the existing add method cannot be used directly.

2.2 Method overloading concept

In Java, method overloading (Method Overloading) means that multiple methods with the same name can exist in the same class, but their parameter lists are different. Through method overloading, different method implementations can be called according to different parameters passed in, providing a more flexible and convenient way to handle different situations.

The rules for method overloading are as follows:

  • The method names must be the same.
  • The method parameter lists must be different, and can be distinguished by the number, type, or order of parameters.

Method overloading has nothing to do with whether the return type is the same

Two methods cannot be overloaded just because the return value type is different

Here is an example to illustrate the concept of method overloading:

public class MyClass {
    public static void main(String[] args) {
        int sum1 = addNumbers(2, 3);
        double sum2 = addNumbers(2.5, 3.8);
        int sum3 = addNumbers(1, 2, 3);
        
        System.out.println("Sum1: " + sum1);
        System.out.println("Sum2: " + sum2);
        System.out.println("Sum3: " + sum3);
    }
    
    public static int addNumbers(int a, int b) {
        return a + b;
    }
    
    public static double addNumbers(double a, double b) {
        return a + b;
    }
    
    public static int addNumbers(int a, int b, int c) {
        return a + b + c;
    }
}

3. Recursion

3.1 Stories from life

Once upon a time, there was a mountain, and there was a temple on the mountain. In the temple, an old monk told a story to the young monk, which was:

“Once upon a time there was a mountain, and there was a temple on the mountain. In the temple, there was an old monk who told a story to the young monk. What he told was:

“Once upon a time there was a mountain, and there was a temple on the mountain…”

“Once upon a time there was a mountain…” “

The above two stories have a common feature: self contains itself, this kind of thinking is very useful in mathematics and programming, because sometimes, the problems we encounter are directly related to the It is not easy to solve, but it is found that after splitting the original problem into its sub-problems, the sub-problems have the same solution as the original problem, and after the sub-problems are solved, the original problem will be solved.

3.2 The concept of recursion

A method that calls itself during execution is called “recursive”.

Recursion is equivalent to “mathematical induction” in mathematics, there is an initial condition, and then there is a recursive formula.

For example, we ask for N!

Start condition: When N = 1, N! is 1. This start condition is equivalent to the end condition of recursion.

Recursive formula: Find N!, it is not easy to find directly, you can convert the problem into 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

Code example: Recursively find the factorial of N

3.3 Recursive Execution Process Analysis

The execution process of the recursive program is not easy to understand. To understand the recursion clearly, you must first understand the “execution process of the method”, especially “After the method execution is completed, return to the calling position and continue to execute”.

public class Test{
    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("end of function, n = 1 ret = 1");
            return 1;
        }
        int ret = n * factor(n - 1);
        System.out.println("end of function, n = " + n + " ret = " + ret);
        return ret;
    }
}

Execution Process Diagram

The program is executed in the order of (1) -> (8) identified in the sequence number

About “Call Stack”

When a method is called, there will be a “stack” memory space to describe the current calling relationship. It is called the call stack.

Each method call is called a “stack frame”, each stack frame contains the parameters of this call, where to return to continue execution and other information.

Later, we can easily see the contents of the call stack with the help of IDEA.

3.4 Recursive Exercise

Code Example 1 Prints each digit of a number in order (eg 1234 prints 1 2 3 4)

public class Test {
    public static void print(int n) {
        if (n >= 10) {
            print(n / 10);
        }
        System.out.print(n % 10 + " ");
    }
    public static void main(String[] args) {
        print(1234567);
    }
}

Code Example 2 Recursively find 1 + 2 + 3 + … + 10

public class Test {
    public static int sum(int n) {
        if(n==1){
            return 1;
        }
        return n + sum(n-1);
    }
    public static void main(String[] args) {
        int ret = sum(10);
        System.out.println(ret);
    }
}

Code Example 3 Write a recursive method that takes as input a non-negative integer and returns the sum of the numbers that make it up. For example, if you input 1729, it should return 1 + 7 + 2 + 9, whose sum is 19

public class Test {
    public static int add(int n) {
        if (n < 10) {
            return n;
        }
        return n % 10 + add(n / 10);
    }
    public static void main(String[] args) {
        int ret = add(12345);
        System.out.println(ret);
    }
}