0

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?

3
  • 7
    Why would Goodbye 1-10 get printed if that only happens when n is 0 (or less)? Commented May 25, 2017 at 9:19
  • 3
    When it enters in if statement, Why do you expect it to execute else statement as well? Commented May 25, 2017 at 9:19
  • 0 is only reached once, hence only once the else branch is executed. The stack unwinding happens 11 times in both versions, only without else 10 extra prints are added. Commented May 25, 2017 at 9:22

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! Much appreciated :)
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.