当前位置:网站首页>Recursive execution mechanism

Recursive execution mechanism

2022-07-05 00:26:00 The learning path of Java Rookies

recursive

Recursion is a method that calls itself

The rules

 1. When executing a method , Just create a new protected independent space ( Stack space )
 2. The local variables of the method are independent , No interaction 
 3. If a reference data type variable is used in the method , Will share data of this reference type 
 4. Recursion must have an end condition , Otherwise, there will be stack overflow 
 5. Recursion takes up a lot of memory 
 6. When a method is executed , Or meet return, It will return , Follow who calls , Just return the results to who , At the same time, when the method is completed or returned , This method is finished 
 

The execution mechanism of recursive call

public class Recursion01 {
    

// Write a  main  Method 
public static void main(String[] args) {
    

T t1 = new T();
t1.test(4);// What output ? n=2 n=3 n=4
 
}
}

class T {
    
// analysis 
public   void test(int n) {
    
if (n > 2) {
    
test(n - 1);
}
System.out.println("n=" + n);
}
 
 



}

Take the one above as an example :
First of all to enter main Method , Then open up space in the stack memory , Then perform main Code snippets in the method , When main Method call test() Method time , Will open up a new space in the stack , Then put the arguments 4 Pass in

because ,if(n>2) The judgment condition is true, So it will execute test(n-1) Method , Open up a new space in the stack , until n=2 When , The judgment is not true , At this point, the console outputs 2, then n=2 This method is over , This stack space will be released , Back to n = 3 Of this space text(n -1); Continue with the following statement , Until the end of the program .
 Insert picture description here

原网站

版权声明
本文为[The learning path of Java Rookies]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202141125149342.html