-2

I am trying to understand how recursive works. Below is a code of If-else block.

 public class Test {

     public void test(int count){
         if(count ==1){

        System.out.println("Inside IF");

     }

     else{
              System.out.println("Inside Else");
              test(--count);
              System.out.println("TEST");

       }
           }


      public static void main(String[] args) {

            Test t = new Test();
             t.test(5);
       }


         }

The Output for the above code is

Inside Else Inside Else Inside Else Inside Else Inside IF TEST TEST TEST TEST

Could someone please help me understand why the TEST has been printed 4 times.

Thanks

2 Answers2

1

test(5) -> "Inside Else" -> test(4) -> "Inside Else" -> test(3) -> "Inside Else" -> test(2) -> "Inside Else" -> test(1) -> Inside If"

At this point, you were "Inside Else" 4 times. There are 4 pending PrintLn("Tests") which need to be processed.

"Test" "Test" "Test" "Test"

0

When you call method b from with method a, method a (the calling method) doesn't just end, it waits until b finishes and then it continues on its merry way. In your case, you're calling the same method each time - each of those methods waits for the method it called to finish. So, when you call t.test(5), it falls into the else block where it calls test(4), so your original call of t.test(5) is waiting for test(4) to finish. But test(4) will call test(3) and wait for it to finish. test(3) calls test(2), which waits. Then test(2) calls test(1) and the magic happens.

test(1) will fall into the if-block and execute System.out.println("Inside IF");, but there's nothing else to execute so it will return. test(2) has been waiting for test(1) to return, which it now has, so it will continue on and execute the next line of code from where it was at, which is System.out.println("TEST");. Nothing else for it to execute, so it returns - to test(3), which was waiting for test(2) to return, so another System.out.println("TEST");. It returns to test(4): another System.out.println("TEST");, and finally to the original t.test(5) in main.