[Java] use of learning notes 4- method
preface
Main contents:
☑️ Understanding and use of methods.
☑️ The understanding and application of recursion.
Tip: the following is the main content of this article. The following cases can be used for reference
1, Basic usage of method
1. What is the method
A method is a snippet of code Similar to the "function" in C language, each method represents a capability or behavior
Significance of the method:
one ️⃣ It is a modular organization code (when the code scale is complex)
two ️⃣ The code can be reused, and a code can be used in multiple locations
three ️⃣ Make the code easier to understand
four ️⃣ Directly call the existing methods for development, and there is no need to build wheels repeatedly
Example: a method to judge whether a number is a prime number
/** * Judge whether the number a is prime *Method name: primeNmb */ public static void primeNmb(int a) { boolean flag = true; for (int n = 2; n < a; n++) { if (a % n == 0) { flag = false; break; } } if (flag) { System.out.println("yes"); } else { System.out.println("no"); } }
2. Method definition syntax
Basic grammar
// Method definition public static Method return value method name([Parameter type parameter ...]){ Method body code; [return Return value]; } // Method call Return value variable = Method name(Argument...);
Example: write a method to add two integers
public class Test1 { public static void main(String[] args) { int a = 10; int b = 5; int sum = add(a, b); //Method call System.out.println("sum = " + sum); } //Definition of method public static int add(int x, int y) { return x + y; //Return value of method } } //results of enforcement sum=15
be careful
one ️⃣ public and static keywords have specific meanings here
two ️⃣ When a method is defined, the parameter may not be When there are parameters, the type of each parameter should be specified
three ️⃣ The parameters when a method is defined are called "formal parameters", and the parameters when a method is called are called "arguments"
four ️⃣ The method definition must be in the class, and the code can be written above or below the calling position
five ️⃣ There is no concept of "function declaration" in Java. Once a method is defined, its implementation must be written
six ️⃣ When defining a method, whether there is a return value depends on the function of the method. If there is no return value, the return value type should be written as void. Return can be used to end the method call in advance
3. Execution process of method call
Basic rules
⚫ ⒈ method is called through the main method
⚫ A method can be called multiple times
⚫ After the parameter is passed, it will be executed to the method body code
⚫ When the method is called, the actual parameter will be assigned to the formal parameter
⚫ When defining a method, the code of the method will not be executed It is executed only when called
⚫ When the method is executed (encounter the return statement), the execution is completed. Return to the method calling position and continue to execute
Example: add two integers
public class Test1 { //Main method public static void main(String[] args) { int a = 10; int b = 5; System.out.println("Before the method is called for the first time"); int sum1 = add(a, b); //Method call System.out.println("After the first method call"); System.out.println("sum1 = " + sum1); System.out.println("Before the second method call"); int sum2 = add(13, 12); //Method call System.out.println("After the second method call"); System.out.println("sum2 = " + sum2); } //Definition of method public static int add(int x, int y) { return x + y; //Return value of method } } //results of enforcement Before the method is called for the first time Calling method x=10,y=5 After the first method call sum1 = 15 Before the second method call Calling method x=13,y=12 After the second method call sum2 = 25
Example: calculate 1+ 2! + 3! + 4! + 5! Use method, avoid using double loop, make the code simpler and clearer
public class Test2 { //Main method public static void main(String[] args) { int sum = 0; for (int i = 1; i <= 5; ++i) { sum += factor(i);//Call the method of factoring i } System.out.println("sum=" + sum); } //A method of calculating a factorial of numbers public static int factor(int n) { System.out.println("calculation" + n + "Factorial!"); int result = 1; for (int j = 1; j <= n; ++j) { result *= j; } return result; } } //results of enforcement Calculating factorial of 1! Calculate the factorial of 2! Calculate the factorial of 3! Calculate the factorial of 4! Calculate the factorial of 5! sum=153
4. Understand the relationship between arguments and formal parameters
Error example: exchange two integer variables (this code does not complete the data exchange.)
public class Test3 { //Main method public static void main(String[] args) { int a = 10; int b = 15; swap(a, b);//Call exchange method System.out.println("a = " + a + ",b = " + b); } //Method of exchanging two integer variables public static void swap(int x, int y) { int tmp = x; x = y; y = tmp; } } //results of enforcement a = 10,b = 15
Cause analysis
The production parameter transfer of Java method is only the transfer of value. For the basic type, the formal parameter is equivalent to the copy of the actual parameter That is, call by value
int a = 10; int b = 20; //Value transmission int x = a; int y = b; hand over x and y Value of int tmp = x; x = y; y = tmp;
As you can see, the modification of x and y does not affect a and b
Correct example: exchange two integer variables (pass reference type parameters, such as arrays to solve this problem)
public class Test3 { //Main method public static void main(String[] args) { int[] arr = {10, 15}; //Before exchange: System.out.println("Before exchange: a = " + arr[0] + ",b = " + arr[1]); swap(arr);//Call exchange method //After exchange System.out.println("After exchange: a = " + arr[0] + ",b = " + arr[1]); } //Method of exchanging two integer variables public static void swap(int[] arr) { int tmp = arr[0]; arr[0] = arr[1]; arr[1] = tmp; } } //results of enforcement Before exchange: a = 10,b = 15 After exchange: a = 15,b = 10
2, Overloading of methods
Sometimes when we need to use a function that is compatible with multiple parameters at the same time, we can use method overloading
1. Problems to be solved by overloading
Examples of errors:
public class Test4 { public static void main(String[] args) { int a = 10; int b = 20; int sum = add(a, b); System.out.println("sum = "+sum); double a2 = 10.5; double b2 = 20.5; double sum2 = add(a2, b2); System.out.println("sum2 = "+sum2); } public static int add(int x, int y) { return x + y; } } //Compilation error Test.java:13: error: Incompatible types: from double Convert to int There may be losses
Note: the existing add method cannot be used directly because the parameter types do not match
2. How to use overloading
Correct example:
public class Test4 { public static void main(String[] args) { int a = 10; int b = 20; int sum = add(a, b); System.out.println("sum = " + sum); double a2 = 10.2; double b2 = 10.3; double sum2 = add(a2, b2); System.out.println("sum2 = " + sum2); double a3 = 10.5; double b3 = 10.5; double c3 = 20.5; double sum3 = add(a3, b3, c3); System.out.println("sum3 = " + sum3); } //The method parameter type is int, and the two numbers are added public static int add(int x, int y) { return x + y; } //The method parameter type is double, and the two numbers are added public static double add(double x, double y) { return x + y; } //The method parameter type is double, and three numbers are added public static double add(double x, double y, double z) { return x + y + z; } } //results of enforcement sum = 30 sum2 = 20.5 sum3 = 41.5
Methods are called add However, some add is the addition of int and some double; Some calculate the addition of two numbers, others calculate the addition of three numbers
Conclusion: the same method name provides different versions of implementation, which is called method overloading
Q: why can all types be received in the println method?
A: because N overloaded methods are defined in the println method
3. Overload rules
For the same class:
⚫ same method name
⚫ different parameters of the method (number of parameters or parameter type)
⚫ The return value type of the method does not affect overloading
Examples of errors:
public class Test4 { public static void main(String[] args) { int a = 10; int b = 20; int sum = add(a, b); System.out.println("sum = " + sum); double a2 = 10.2; double b2 = 10.3; double sum2 = add(a2, b2); System.out.println("sum2 = " + sum2); } //The method parameter type is int, and the return value is int public static int add(int x, int y) { return x + y; } //The method parameter type is int and the return value is double public static double add(int x, int y) { return x + y; } } //Compilation error java: Already in class example_2_18.Test4 Methods are defined in add(int,int)
Note: when two methods have the same name and parameters, but the return values are different, it does not constitute an overload
4. The difference between method overloading and method rewriting
Method overload is a compile time polymorphism:
Occurs in the same class, the method name is the same, the parameter list is different (different parameter types, different numbers, different orders), and has nothing to do with the method return value and access modifier, that is, overloaded methods cannot be distinguished according to the return type
Method overrides are runtime polymorphisms:
When it occurs in parent-child classes, the method name and parameter list must be the same, the exception thrown is less than or equal to the parent class, and the access modifier is greater than or equal to the parent class (Richter substitution principle); If the method access modifier of the parent class is private, it is not overridden in the subclass.
3, Method recursion
1. The concept of recursion
When a method calls itself in the process of execution, it is called "recursion".
Those scenarios can be solved by recursion:
one ️⃣ The solution of a large problem can be divided into the solution of multiple subclass problems;
two ️⃣ After splitting, the subclass problem and the original problem have the same solution ideas except for the different data scale;
three ️⃣ Recursive termination condition exists
Basic idea of writing recursive method:
⚫ When writing recursive methods, you must pay attention to the semantics of the method (function of the method)
⚫ Don't worry about how to implement the specific process of recursion, but how to use this method to solve the problem
⚫ Don't deliberately think that recursion is calling yourself, just as you are calling methods written by others
2. Recursive execution process
It is not clear to understand the "recursive method" after the "recursive method" is called, especially if you want to continue the execution of the procedure, you must understand the "recursive method" first
Example: recursively find the factorial of N, plus the log version
public class Test5 { 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; } } //results of enforcement Function start, n = 5 Function start, n = 4 Function start, n = 3 Function start, n = 2 Function start, n = 1 End of function, n = 1 ret = 1 End of function, n = 2 ret = 2 End of function, n = 3 ret = 6 End of function, n = 4 ret = 24 End of function, n = 5 ret = 120 ret = 120
Execution process diagram: (the program is executed in the order of (1) - > (8) identified in the serial number)
About "call stack"
When the method is called, there will be a memory space such as "stack" to describe the current call relationship Called call stack
Every method call is called a "stack frame". Each stack frame contains the parameters of this call, where to return and continue execution Later, we can easily see the contents of the call stack with the help of IDEA
3. Recursive exercise
Code example 1: print each digit of a number in sequence (for example, 1234 prints 1 2 3 4)
public class Test6 { public static void main(String[] args) { int num = 12345; print(num); } public static void print(int num) { if (num > 9) { print(num / 10); System.out.print(" "); } System.out.print(num % 10); } } //results of enforcement 1 2 3 4 5
Code example 2: recursively find 1 + 2 + 3 +... + 10
public class Test7 { public static void main(String[] args) { int num = 10; System.out.println(sum(num)); } public static int sum(int num) { if (num == 1) { return 1; } return num + sum(num - 1); } } //results of enforcement 55
Code example 3: write a recursive method, enter a non negative integer and return the sum of the numbers that make up it For example, if you enter 1729, you should return 1 + 7 + 2 + 9, and its sum is 19
public class Test8 { public static void main(String[] args) { int num = 1729; System.out.println(sum(num)); } public static int sum(int num) { if (num < 10) { return num; } return num % 10 + sum(num / 10); } } //results of enforcement 19
Code example 4: find the nth item of Fibonacci sequence
public class Test9 { public static void main(String[] args) { int n = 40; System.out.println(fib(n)); } public static int fib(int n) { if (n == 1 || n == 2) { return 1; } return fib(n - 1) + fib(n - 2); } } //results of enforcement 102334155
When we ask for b(40), we find that the execution speed of the program is very slow The reason is that a large number of repeated operations are carried out
public class Test10 { public static int count = 0; // This is the member variable of the class Here, it is used to calculate the number of repeated executions of fib(3) public static void main(String[] args) { System.out.println(fib(40)); System.out.println(count); //fib(3) number of repetitions } public static int fib(int n) { if (n == 1 || n == 2) { return 1; } if (n == 3) { count++; } return fib(n - 1) + fib(n - 2); } } //results of enforcement 102334155 39088169 // fib(3) was repeated 30 million times
The Fibonacci sequence problem can be solved in a circular way to avoid redundant operation and greatly improve the execution efficiency of the program
public static int fib(int n) { int last2 = 1; int last1 = 1; int cur = 0; for (int i = 3; i <= n; i++) { cur = last1 + last2; last2 = last1; last1 = cur; } return cur; }
Summary:
⚫ Recursion is an important way of programming to solve problems
⚫ Some problems are naturally defined by recursion (such as Fibonacci sequence, binary tree, etc.), so it is easy to use recursive solution
⚫ Some problems can be solved by using recursion and non recursion (loop) Then it is more recommended to use loops at this time. Non recursive programs are more efficient than recursion
summary
Study notes. If there is anything wrong with the content, please correct it! (all contents are for reference only)