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?
ifstatement, Why do you expect it to execute else statement as well?else10 extra prints are added.