[Java | Basics] Method definition, usage, overloading and recursion

1. What is a method

A method is an organized, reusable specific block of code (similar to a function) with a certain function

When we usually write code, if we encounter some code with the same function that we will often use, we can write this code as a method, and call the method directly when we use it next time. There is no need to use it every time Rewrite the code again.

2. Definition and use of methods

// 语法:
修饰符 返回值类型 方法名称([参数类型 形参 ...]){
    
    
	方法体代码;
	return 返回值;
}
  • Modifiers: There are many modifiers for methods, such as access restriction modifiers, static, final, etc.
  • Return value type: Limit the type of return value
  • parameter type: the type used to qualify the formal parameter
  • Formal parameters: used to receive incoming variables
  • return: return a value and end the method

If I often need to add and sum two numbers when writing code, then I can write a method to achieve this function.
For example:

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

When a method is defined, the code of the method will not be executed. It will only be executed when it is called.
Example of a method call:

    public static void main(String[] args) {
    
    
        int ret = add(1,2);
        System.out.println(ret);
    }
    // 输出结果: 3

A method can be called multiple times.

使用方法的好处:

  • Avoid code duplication and improve development efficiency
  • It is easy to maintain, when you need to change, you only need to modify the method

Note: Functions cannot be defined nestedly, and there is no method declaration in Java

return type

For the return value type of the method, you can set it according to your own needs.
Example: If you want to return the largest number among the two numbers.
At this time, if we want to get this number, we can return the maximum value.
The code is as follows:

    public static int getMax(int n,int m){
    
    
        return n > m? n : m;
    }

But if we just want to output the maximum value of the two numbers, then there are two options at this time: 1. Output directly in the method body 2. Return the maximum value and output it in the main method. The code is as follows
:

    public static int getMax1(int n,int m){
    
    
        return n > m? n : m;
    }
    public static void getMax2(int n,int m){
    
    
        int ret = n > m ? n : m;
        System.out.println(ret);
    }
    public static void main(String[] args) {
    
    
        int ret = getMax1(7,6);
        System.out.println(ret);
        getMax2(7,6);
    }

Formal Participation Arguments

Demonstrate with the code just now:
insert image description here
the formal parameter is the variable in () when defining the method. The function of the formal parameter is only to receive the value passed by the actual parameter . The name of the formal parameter is arbitrary and has no effect on the method.
See the figure below :
insert image description here
The swap function is used to exchange the values ​​of n and m. It can be seen that n and m are exchanged successfully in the method body, but calling the swap method in the main method to exchange the values ​​of a and b has no effect. Why What?
In fact, it is because when the actual parameter is passed to the formal parameter, it just passes the value, and the formal parameter can be a copy of the actual parameter. Therefore, the essence of the swap function is only to exchange the formal parameter and will not affect the real parameter. Parameter. But the reference type can be exchanged, the most typical one is an array, put these two numbers in the array, and exchange the values ​​of the two subscripts in the array. It will be explained later, so I won’t go into details here.

method execution process

调用方法->传递参数->找到方法地址->执行被调方法的方法体->被调方法结束返回->回到主调方法继续往下执行

3. ⭐ Method overloading

What is method overloading?
It can be simply understood as "一词多义"the add method just now. It is just adding two integers. If I write another add method, I want to add three integers, or two floating point numbers. to add. This 方法名不变,形参的个数 顺序不一样就构成了方法的重载
example:

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

This is method overloading
注意:

  • Method overloading has nothing to do with the return value
  • The parameter lists cannot be the same (the order of the number of formal parameters, etc.)
  • method names must be the same

4. Recursion

Recursion refers to the method of using the function itself in the definition of the function.

Next, through an example to understand the following recursion

Example: Input an n, find the factorial of n

Solution 1: Use a loop to solve

    public static int factorial(int n){
    
    
        int ret = 1;
        for (int i = 1; i <= n; i++) {
    
    
            ret *= i;
        }
        return ret;
    }

But now we are talking about factorial, let's look at the recursive solution method.

    public static int factorial(int n){
    
    
        if (n == 1){
    
    
            return 1;
        }
        return n*factorial(n-1);
    }

Running screenshot:
insert image description here
The following is the process of factorial(5) at runtime:
insert image description here
when n is not equal to 1, execute n * factorial(n-1). When n is equal to 1, return 1. Then start from the last layer and move forward Return and return the final result.
Recursion is still quite difficult at the beginning of contact. It is recommended to sort out the recursive execution process to help better understand recursion

5. Summary

There are many methods used in actual development, and it is necessary to focus on mastering overloading and recursion.

Thank you for watching! I hope this article can help you!
The Java column is constantly being updated, welcome to subscribe!
"Wish to encourage you and work together!"
insert image description here

Guess you like

Origin blog.csdn.net/m0_63463510/article/details/129199112