简体   繁体   中英

Does java create all the stack frames for recursion before printing the code for the user?

So here is a simple example of recursion where we count down from a number. When clicking run does java calculate 5,4,3,2,1,0 store those numbers in 6 stack frames only then does it print the code? Or maybe it calculates 5, adds it to call stack, 4 adds it to call stack etc...

public static void main(String[] args) {
   countDown(5);
}
public static void countDown(int n){
 if(n <= 0){
     System.out.println(n);
 }
 else{
     System.out.println(n);
     --n;
     countDown(n);

     //Call stack pops 5 times from the 5 calls from here up until the method call
     //Test will print 5 times
     System.out.println("Test");
      }
 }

Yes, you can see it for yourself using the Thread.currentThread().getStackTrace() method:

import java.util.Arrays;

class StackFrames {

  public static void main(String[] args) {
     countDown(5);
  }
  public static void countDown(int n){
   if(n <= 0){
       System.out.println(n);
   } else{
       System.out.println(n);
       --n;
       countDown(n);


       //Call stack pops 5 times from the 5 calls from here up until the method call
       //Test will print 5 times
       System.out.println("Test");
       Arrays.stream(
          Thread
          .currentThread()
          .getStackTrace()
      ).forEach(System.out::println);

   }
 }
}

Output:

5
4
3
2
1
0
Test
java.base/java.lang.Thread.getStackTrace(Thread.java:1610)
StackFrames.countDown(StackFrames.java:18)
StackFrames.countDown(StackFrames.java:12)
StackFrames.countDown(StackFrames.java:12)
StackFrames.countDown(StackFrames.java:12)
StackFrames.countDown(StackFrames.java:12)
StackFrames.main(StackFrames.java:4)
Test
java.base/java.lang.Thread.getStackTrace(Thread.java:1610)
StackFrames.countDown(StackFrames.java:18)
StackFrames.countDown(StackFrames.java:12)
StackFrames.countDown(StackFrames.java:12)
StackFrames.countDown(StackFrames.java:12)
StackFrames.main(StackFrames.java:4)
Test
java.base/java.lang.Thread.getStackTrace(Thread.java:1610)
StackFrames.countDown(StackFrames.java:18)
StackFrames.countDown(StackFrames.java:12)
StackFrames.countDown(StackFrames.java:12)
StackFrames.main(StackFrames.java:4)
Test
java.base/java.lang.Thread.getStackTrace(Thread.java:1610)
StackFrames.countDown(StackFrames.java:18)
StackFrames.countDown(StackFrames.java:12)
StackFrames.main(StackFrames.java:4)
Test
java.base/java.lang.Thread.getStackTrace(Thread.java:1610)
StackFrames.countDown(StackFrames.java:18)
StackFrames.main(StackFrames.java:4)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM