Java recursion in detail

Detailed recursion:

1. Recursion In a word, it is a process in which a method automatically calls itself repeatedly.

2. Because it is calling itself repeatedly, it looks like a loop, so in order to avoid memory overflow system crash, we need to add a return value judgment to the method to jump out of the recursive loop.


Let's use debug mode to explain the implementation principle of recursion:

The first is the source code:

public class Demo8 {
	public static void main(String[] args) {          
            System.out.println(sum(1));  
	}  
/**
* @param summation method
*/  
	public static int sum(int num){  
		if(num == 100){  
			return 100;  
		}  
		return num + sum(num+1);  
		}  
	}  

We call sum on line 5 of the code to sum the values ​​from 1 to 100

Lines 11 and 12 in the code are the ifs that jump out of the recursion, and the value to jump out is 100.

Line 14 in the code is the implementation of recursion.


Now let's analyze it in debug mode:

first step:


First, we run the debug debugging. In the debug, we can see that the method that has called a sum instance has been called. In the Value on the right, we can see that the parameter value in the method is exactly the 1 we entered. Now entering the method and executing the if judgment, since the num value is not 100, the return 100 in the if is not executed; the program will continue to run down.

Step 2:


We can see that the parameter value 1 in the 14th line of the code has been saved in num, and the code will continue to run to sum(num+1). We can see that a sum has been created in the debug debugging box above. method, we will see that the value in Value on the right is 2, which is because the value in num is incremented by +1. So the current value of num is equal to 2 and saved to num in the second sum method.

Then you can continue to think, the second sum method will create a third sum method, the third sum method will create a fourth sum method, and the self-incremented value after creation will be saved to the current sum In the int num in the method.

Let's take a look at the animation effect:



Finally, after 100 runs, if will return the value of 100, the method will not continue to execute to line 14, so it will not create a new sum method. Recursion also jumps out. Let's take a look at the animation:


We can see that when the value in num increases to 100, the if method is executed, and a value of 100 is returned. The recursion is directly jumped out, so what is the subsequent code executing? Subsequent code will continue to perform the addition of num values ​​in each sum method, and you can also clearly see that each instanced sum method is eliminated. until all are added. The final value can also be seen in the Value or the console is 5050.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325733816&siteId=291194637