Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Can you please explain this output - Kind of recursion

 
Krishna Rao
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When I executed the java code given below, its giving the output as shown below the program. One thing really confuses me.

Why "After calling retry() ==> 3" is printed thrice and that too in a serial order at the end of the execution ?

I mean based on the value of i, I feel that "System.out.println("After calling retry() ==> " + i);" is executed at the end.

How is this possible ? Can somebody explain

public class TryRecur{
static int i=0;
static void retry(){

try{
if (i<3) throw new Exception();
System.out.println("After throwing excetpion ==> " + i);
}catch(Exception e){
i++;
System.out.println("In Catch ==> " + i);
retry();
System.out.println("After calling retry() ==> " + i);
}
}

public static void main(String[] args){
TryRecur.retry();
}
}

Output:
In Catch ==> 1
In Catch ==> 2
In Catch ==> 3
After throwing excetpion ==> 3
After calling retry() ==> 3
After calling retry() ==> 3
After calling retry() ==> 3
 
dinesh Venkatesan
Ranch Hand
Posts: 134
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Krishna,

We know that when a method is invoked the control jumps to the called method and after finishing, the control will reach the same place from where the flow is broken. Since the control flows three times after finishing it comes back three times and gets printed.

Hope this helps.
dinesh.
 
Krishna Rao
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Dinesh. I understand that.
But it should have been 1,2,3 right ? I might be totally wrong.

Please clarify.
 
Joanne Neal
Rancher
Posts: 3742
16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In retry(), if i is less than 3 you call retry() again, so you will never return from a call to retry() until i equals 3. So when i equals 3 you return from retry() and print the value of i (which is 3).

If you want to maintain a different value of i for each call to retry(), then you need to pass i as a parameter
Try this
 
Krishna Rao
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Joanne. It clarifies.

Regards
-Krishna Rao
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic