[JAVA] Take you to know java methods | methods in java & methods in overloading and recursion

Author's homepage: paper jie's blog

Author of this article: Hello everyone, I am paper jie, thank you for reading this article, welcome to build three companies.

This article is included in the "JAVASE Grammar Series" column, which is carefully crafted for college students and beginners in programming. The author spent a lot of money (time and energy) to build it, and wiped out the basic knowledge of javaSE, hoping to help readers.

Other columns: "Detailed Algorithm Explanation", "C Language", etc.

Content sharing: This issue will give a preliminary and general explanation of the JAVA language~

Definition, use and understanding of JAVA methods

What is a method in Java

A method is a code fragment. It is very similar to a "function" in C language. Its role in Java can be understood as a function in C language.

Meaning of method existence:

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.

For example: to develop a calculator now, in the calculator it is often necessary to judge the addition of two numbers

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

The above code can also be defined by methods in java, which is more convenient to use.

method definition 

method syntax format

Modifier return value type method name ([parameter type parameter...]) { method body code; [return return value]; }


Here is a chestnut : implement a method to add two numbers

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

【Precautions】

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 

Execution process of method call

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 

Notice:

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 

Give a chestnut: add two numbers

public class Method {
    public static void main(String[] args) {
        int a = 10;
        int b = 20;
        System.out.println("第一次调用方法之前");
        int ret = add(a, b);
        System.out.println("第一次调用方法之后");
        System.out.println("ret = " + ret);
        System.out.println("第二次调用方法之前");
        ret = add(30, 50);
        System.out.println("第二次调用方法之后");
        System.out.println("ret = " + ret);
    }
    public static int add(int x, int y) {
        System.out.println("调用方法中 x = " + x + " y = " + y);
        return x + y;
}
}

Another example: calculate 1! + 2! + 3! + 4! + 5!

public class TestMethod {
    public static void main(String[] args) {
        int sum = 0;
        for (int i = 1; i <= 5; i++) {
        sum += fac(i);
        } 
        System.out.println("sum = " + sum);
    }
    public static int fac(int n) {
        System.out.println("计算 n 的阶乘中n! = " + n);
        int result = 1;
        for (int i = 1; i <= n; i++) {
        result *= i;
        } 
        return result;
    }
}

Using the method here, we can avoid using multiple repetitions. To calculate and use this method, the code can be simpler and clearer 

Relationship between Formal Parameters and Actual Parameters 

The formal parameter of the method is equivalent to the argument in the mathematical function, and 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 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 value passed when the method is called. 

public static int getSum(int N){ // N是形参
return (1+N)*N / 2;
} 
getSum(10); // 10是实参,在方法调用时,形参N用来保存10
getSum(100); // 100是实参,在方法调用时,形参N用来保存100
public static int add(int a, int b){
return a + b;
} a
dd(2, 3); // 2和3是实参,在调用时传给形参a和b

This is like a juicer. The actual parameter is the fruit we want to put in, and the formal parameter is the position where the fruit is put in the machine. It can put a variety of fruits. It depends on your choice. The fried juice is the value of our return. .

                                    

One point to note here: 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. This is different from the C language, which can pass pointers, but Java cannot, because it has no pointers. 

Take a chestnut:

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);
}
} 
// 运行结果
swap: x = 20 y = 10
main: a = 10 b = 20

By running the code, we can know 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 values ​​​​in the actual parameters a and b are copied A copy is passed to the formal parameters x and y, so operations on the formal parameters x and y will not have any effect 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, call by value 

Solution  

We can use an array to solve:

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;
}
} /
/ 运行结果
arr[0] = 20 arr[1] = 10

method of void type

The return value of the method is optional. Sometimes it can be absent, and when there is no return value type, it must be written as void  

Take a chestnut:

class Test {
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);
}
}

method overloading 

The meaning of method overloading

Go directly to the code:

public class TestMethod {
public static void main(String[] args) {
int a = 10;
int b = 20;
int ret = add(a, b);
System.out.println("ret = " + ret);
double a2 = 10.5;
double b2 = 20.5;
double ret2 = add(a2, b2);
System.out.println("ret2 = " + ret2);
}
public static int add(int x, int y) {
return x + y;
}
} /
/ 编译出错
Test.java:13: 错误: 不兼容的类型: 从double转换到int可能会有损失

We found that the existing add method cannot be used directly because the parameter types do not match. Then without overloading the method, we can only violently write multiple different codes:

public class TestMethod {
public static void main(String[] args) {
int a = 10;
int b = 20;
int ret = addInt(a, b);
System.out.println("ret = " + ret);
double a2 = 10.5;
double b2 = 20.5;
double ret2 = addDouble(a2, b2);
System.out.println("ret2 = " + ret2);
}
public static int addInt(int x, int y) {
return x + y;
}
public static double addDouble(double x, double y) {
return x + y;
}
}

This can indeed solve the problem, but the bad thing is that you need to provide many different method names, and choosing a name is a headache. Can all the names be given as add? Here we need to use the knowledge of our method overloading.

What is method overloading

In natural language, if a word has multiple meanings, it is said that the word has been overloaded. The specific meaning needs to be combined with specific scenarios, such as being rejected when expressing love to girls. Excellent, but I don't want to be in a relationship yet. Hey, good people and excellent here have become derogatory terms.

Methods can also be overloaded in Java. In java, if multiple methods have the same name but different parameter lists, the methods are said to be overloaded 

public class TestMethod {
public static void main(String[] args) {
add(1, 2); // 调用add(int, int)
add(1.5, 2.5); // 调用add(double, double)
add(1.5, 2.5, 3.5); // 调用add(double, double, double)
}
public static int add(int x, int y) {
return x + y;

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

Note here:

1. The method names must be the same

2. The parameter lists must be different (the number of parameters is different, the types of parameters are different, and the order of types must be different)

3. It has nothing to do with whether the return value type is the same 

// 注意:两个方法如果仅仅只是因为返回值类型不同,是不能构成重载的
public class TestMethod {
public static void main(String[] args) {
int a = 10;
int b = 20;
int ret = add(a, b);
System.out.println("ret = " + ret);
}
public static int add(int x, int y) {
return x + y;
}
public static double add(int x, int y) {
return x + y;
}
} /
/ 编译出错
Test.java:13: 错误: 已在类 Test中定义了方法 add(int,int)

When the compiler compiles the code, it will deduce the actual parameter type, and determine which method to call according to the deduction result, so you don’t have to worry about it not knowing which function to use, the compiler is very smart~

method signature 

This is not the autograph signed by a celebrity~

You can think about the fact that 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 used here, and 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 

Take a chestnut:

public class TestMethod {
public static int add(int x, int y){
return x + y;
}
public static double add(double x, double y){
return x + y;
}
public static void main(String[] args) {
add(1,2);
add(1.5, 2.5);
}
}

The above code is compiled, and then use the javap disassembly tool that comes with JDK to view

Specific operation:

1. First compile the project to generate a .class bytecode file

2. Enter the directory where the .class to be viewed is located in the console

3. Enter: javap -v bytecode file name 


Special symbols in method signatures: 


 recursion

A fun term about recursion is called: Matryoshka, if you don’t play well, it becomes an infinite doll, and you can’t get out.

The above two pictures have a common feature, that is, they contain themselves. This kind of thinking is very useful in mathematics and programming, because sometimes the problems we encounter are not easy to solve directly, but we find that the original problem After splitting into its sub-problems, the sub-problems have the same solution as the original problem. After the sub-problems are solved, the original problem is solved. This is the recursive solution.

what is recursion 

A method calls itself during execution, which is called "recursion". Recursion is equivalent to "mathematical induction" in mathematics, with an initial condition, and then a recursive formula: 

Seek N!

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

Then the recursive formula: Find N! N! => N * (N-1)! 

Two things to note about recursion:

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

Take a chestnut:

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;
} r
eturn n * factor(n - 1); // factor 调用函数自身
} 

Execution of recursive calls 

To understand recursion clearly, we 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." Here, taking the above code as an example, draw a picture for everyone to analyze:

 The program is executed in the order of the red and purple lines on the way.

Here is a knowledge point of the stack:

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

Each method call is called a "stack frame", and each stack frame contains information about the parameters of this call, where to return to continue execution, and so on.

We can easily see the contents of the call stack with IDEA

 practise

Here are a few recursive practice topics, you can practice if you are interested:

Recursively find 1 + 2 + 3 + ... + 10 

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

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

    public static void prin (int n) {
        if(n<10) {
            System.out.println(n);
            return;
        }
        prin(n/10);
        System.out.println(n%10);
    }

Write a recursive method that takes 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 static int sum(int num) {
if (num < 10) {
return num;
} r
eturn num % 10 + sum(num / 10);
}

Find the Nth term of the Fibonacci sequence  

recursive version

public class Test {
    public static void main(String[] args) {
        System.out.println(fib(6));
    }
    public static int fib(int n) {
        if(n==1 || n==2)
            return 1;
        return fib(n-1) + fib(n-2);
    }

iterative version

The efficiency of the iterative version is much higher than that of recursion, try to use iteration to find fib

    public static void main(String[] args) {
        System.out.println(fib2(6));
    }
    public static int fib2(int n) {
        if(n==1 || n==2) {
            return 1;
        }
        int flg1 = 1;
        int flg2 = 1;
        int flg3 = 0;
        int i = 3;
        while(i<=n) {
            flg3 = flg1 + flg2;
            flg1 = flg2;
            flg2 = flg3;
            i++;
        }
        return flg3;
    }

Guess you like

Origin blog.csdn.net/paperjie/article/details/131962775