1. Basic usage of method
1.1 what is a method
Method is a code fragment, similar to the "function" in C language.
Significance of the method:
- It is a modular organization code (when the code scale is complex).
- The code can be reused, and a copy of the code can be used in multiple locations.
- Make the code easier to understand.
- Directly call the existing methods for development, and there is no need to build wheels repeatedly.
Code example: calculate 1+ 2! + 3! + 4! + 5!
int sum = 0; for (int i = 1; i <= 5; i++) { int tmp = 1; for (int j = 1; j <= i; j++) { tmp *= j; } sum += tmp; } System.out.println("sum = " + sum);
Double loops are used in this code, which is easy to write wrong. Next, we can use methods to optimize the code
1.2 method definition syntax
Basic syntax:
//Method definition
public static method return value method name ([parameter type parameter...]){
Method body code;
[return value];
}
//Method call
Return value variable = method name (argument...);
Code example: implement a method to add two integers
class Test { public static void main(String[] args) { int a = 10; int b = 20; // Method call int ret = add(a, b); System.out.println("ret = " + ret); } // Definition of method public static int add(int x, int y) { return x + y; } } // results of enforcement ret = 30
matters needing attention
- public and static keywords have specific meanings here.
- When defining a method, there can be no parameters, and each parameter needs to specify a type.
- When defining a method, the return value can also be null. If there is no return value, the return value type should be written as void.
- The parameters when a method is defined are called "formal parameters", and the parameters when a method is called are called "arguments".
- The definition of the method must be in the class, and the code can be written above or below the calling position.
- There is no concept of "function declaration" in Java.
1.3 execution process of method call
Basic rules
- When defining a method, the code of the method will not be executed. It will only be executed when calling.
- When the method is called, the argument is assigned to the formal parameter.
- After the parameter is passed, it will be executed to the method body code.
- After the method is executed (encounter the return statement), it is executed. Return to the method call position and continue to execute.
- A method can be called multiple times.
Code example 1: calculate the addition of two integers
class Test { public static void main(String[] args) { int a = 10; int b = 20; System.out.println("Before the method is called for the first time"); int ret = add(a, b); System.out.println("After the first method call"); System.out.println("ret = " + ret); System.out.println("Before the second method call"); ret = add(30, 50); System.out.println("After the second method call"); System.out.println("ret = " + ret); } public static int add(int x, int y) { System.out.println("In calling method x = " + x + " y = " + y); return x + y; } }
Code example 2: calculate 1! + 2! + 3! + 4! + 5!
class Test { 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("calculation n Factorial of! n = " + n); int result = 1; for (int i = 1; i <= n; i++) { result *= i; } return result; } }
Use method, avoid using double loop, and make the code simpler and clearer.
1.4 relationship between arguments and formal parameters
Code example: exchanging two integer variables
class Test { public static void main(String[] args) { int a = 10; int b = 20; swap(a, b); System.out.println("a = " + a + " b = " + b); } public static void swap(int x, int y) { int tmp = x; x = y; y = tmp; } }
From the above running results, we can see that we did not successfully exchange two numbers. The reason for this result is that the formal parameter is equivalent to the copy of the actual parameter for the basic type, that is, the value passing call.
Solution: pass reference type parameters (such as array to solve this problem)
class Test { public static void main(String[] args) { int[] arr = {10, 20}; swap(arr); System.out.println("a = " + arr[0] + " b = " + arr[1]); } public static void swap(int[] arr) { int tmp = arr[0]; arr[0] = arr[1]; arr[1] = tmp; } }
1.5 methods without return value
The return value of the method is optional and sometimes not.
Code example:
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); } }
In addition, the method of exchanging two integers just now has no return value.
2. Method overload
Sometimes when we need to use a function that is compatible with multiple parameters at the same time, we can use method overloading.
2.1 problems to be solved by heavy load
Code example:
class Test { 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; } }
The existing add method cannot be used directly because the parameter types do not match.
Therefore, when creating code, the parameter types must match
Code example:
class Test { 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 way of writing can get the correct results (for example, Go language does this), but Java thinks that the name addInt is unfriendly, so it's better to call it add directly.
2.2 use heavy load
Code example:
class Test { 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); double a3 = 10.5; double b3 = 10.5; double c3 = 20.5; double ret3 = add(a3, b3, c3); System.out.println("ret3 = " + ret3); } 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; } }
The names of methods are all called add. However, some add calculates the addition of int, some double, some two numbers, and some three numbers. The same method name provides different versions of implementation, which is called method overloading.
2.3 overload rules
For the same class:
- Same method name
- Method has different parameters (number of parameters or parameter type)
- The return value type of the method does not affect overloading
Code example:
class task { public static void main(String[] args) { int a = 10; int b = 20; int ret = add3(a, b); System.out.println("ret = " + ret); } public static int add3(int x, int y) { return x + y; } public static double add3(int x, int y) { return x + y; } }
When two methods have the same name and parameters, but the return values are different, they do not constitute an overload.
3. Method recursion
3.1 concept of recursion
When a method calls itself in the process of execution, it is called "recursion".
Recursion is equivalent to mathematical "mathematical induction", with a starting condition and then a recursive formula.
For example, we ask N!
Starting condition: when N = 1, N! Is 1. This starting 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)!
Code example: recursively 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); // factor calls the function itself }
3.2 recursive execution process analysis
The execution process of recursive programs is not easy to understand. To understand recursion clearly, you must first understand the "method execution process", especially "after the method execution is completed, return to the calling position and continue to execute".
Code example: recursively 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) { 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; }
The execution process diagram is as follows:
About "call stack"
When a method is called, there will be a memory space such as "stack" to describe the current call relationship. It is called call stack
Each method call is called a "stack frame". Each stack frame contains the parameters of the call, where to return and continue execution
3.3 recursive summary
- Recursion is an important way to solve programming problems.
- Some problems are naturally defined recursively (such as Fibonacci sequence, binary tree, etc.), so it is easy to use recursive solutions.
- Some problems can be solved by using recursion and non recursion (loop). It is more recommended to use loop at this time. Compared with recursion, non recursive programs are more efficient.
3.4 recursive exercises
3.4.1 recursive factorization of N
public class practice { //Recursively find the factorial of N public static int factorial(int n){ if(n==1) return 1; elsereturn n*factorial(n-1); } public static void main(String[] args) { System.out.println(factorial(5)); } }
3.4.2 recursively find 1 + 2 + 3 +... + 10
public class practice { public static int sumnumber(int n){ if(n==1) return 1; elsereturn n+sumnumber(n-1); } public static void main(String[] args) { System.out.println(sumnumber(10)); } }
3.4.3 print each digit of a number in sequence (for example, 1234 prints 1 2 3 4)
public class practice { public static void number(int n){ if(n<10) System.out.print(n%10+" "); else { number(n / 10); System.out.print(n % 10 + " "); } } public static void main(String[] args) { number(1234); } }
3.4.4 write a recursive method, enter a non negative integer, and return the sum of the numbers that make up it
public class practice { public static int sum(int n){ if (n<10) return n%10; elsereturn sum(n/10)+n%10; } public static void main(String[] args) { System.out.println(sum(12345)); } }
3.4.5 finding the nth item of Fibonacci sequence
public class practice { //Recursively find the nth term of Fibonacci sequence public static int fib(int n){ if(n==1||n==2) return 1; elsereturn fib(n-1)+fib(n-2); } public static void main(String[] args) { System.out.println(fib(8)); } }
3.4.6 solving the Hanoi Tower problem
The Hanoi Tower, also known as the river tower, originates from an ancient Indian legend.
When Brahma created the world, he made three diamond pillars. On one pillar, 64 gold discs were stacked in order of size from bottom to top.
Brahma ordered Brahman to rearrange the disk on another column in order of size from below.
It is also stipulated that the disc cannot be enlarged on the small disc at any time, and only one disc can be moved between the three columns at a time.
How should I operate?
public class practice { public static void move(char pose1,char pose2){ System.out.print(pose1+"->"+pose2+" "); } /* n:Represents the number of plates pose1:Starting position of plate pose2:Transfer position of plate pose3:Final position of plate */public static void hanoi(int n,char pose1,char pose2,char pose3){ if(n==1) move(pose1,pose3); else{ hanoi(n-1,pose1,pose3,pose2); move(pose1,pose3); hanoi(n-1,pose2,pose1,pose3); } } public static void main(String[] args) { hanoi(1, 'A', 'B', 'C'); System.out.println(); hanoi(2,'A','B','C'); System.out.println(); hanoi(3,'A','B','C'); } }
3.4.7 frog jumping steps
A frog can jump up one step or two steps at a time. How many jumping methods does the frog jump up an n-step
public class practice { /* The Fibonacci problem in disguise, but the first is 1, the second is 2, from the second Three starts are the first plus the second *///Frog jumping steps public static int frogJump(int n){ if(n==1||n==2) return n; elsereturn frogJump(n-1)+frogJump(n-2); } public static void main(String[] args) { System.out.println(frogJump(7)); } }