在为用户打印代码之前,java是否会创建所有用于递归的堆栈帧?
这是一个简单的递归示例,我们从一个数字开始倒数。当单击“运行”时,java是否计算5,4,3,2,1,0,然后将这些数字存储在6个堆栈帧中,然后才打印代码?或者它可能计算 5,将其添加到调用堆栈,4 将其添加到调用堆栈等等......
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");
}
}
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");
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,您可以使用 Thread.currentThread().getStackTrace() 方法:
输出:
Yes, you can see it for yourself using the Thread.currentThread().getStackTrace() method:
Output: