Reputation: 163
Reviewing my notes and was wondering if anyone has a concise explanation for what is occurring below:
public class HelloWorld{
public static void main(String[]args){
helloWorld(10);
}
public static void helloWorld(int n){
if(n > 0){
System.out.println("HelloWorld! " + n);
helloWorld(n-1);
}
System.out.println("GoodBye from " + n);
}
}
Output:
HelloWorld! 10
HelloWorld! 9
HelloWorld! 8
HelloWorld! 7
HelloWorld! 6
HelloWorld! 5
HelloWorld! 4
HelloWorld! 3
HelloWorld! 2
HelloWorld! 1
GoodBye from 0
GoodBye from 1
GoodBye from 2
GoodBye from 3
GoodBye from 4
GoodBye from 5
GoodBye from 6
GoodBye from 7
GoodBye from 8
GoodBye from 9
GoodBye from 10
Just to be clear, I totally understand what's happening above with the recursion and the call stack unwinding. My question is about what happens when I include an else statement below:
public static void helloWorld(int n){
if(n > 0){
System.out.println("HelloWorld! " + n);
helloWorld(n-1);
}else{
System.out.println("GoodBye from " + n);
}
}
Output:
HelloWorld! 10
HelloWorld! 9
HelloWorld! 8
HelloWorld! 7
HelloWorld! 6
HelloWorld! 5
HelloWorld! 4
HelloWorld! 3
HelloWorld! 2
HelloWorld! 1
GoodBye from 0
Why does the call stack appear to not unwind when it hits the else statement?
Upvotes: 0
Views: 237
Reputation: 3945
In 2nd case the else block will be executed only for n = 0
as it is going in the if block. However in the first case, after each recursion completes System.out.println("GoodBye from " + n);
will be executed as it is not bound with any condition.
Upvotes: 1
Reputation: 393811
The call stack unwinds in both cases. It just doesn't print anything when it unwinds in the second snippet, since you only print "GoodBye from " + n
when n
is 0, which happens exactly once.
Upvotes: 4