It's not a secret anymore!*
The moose likes Java in General and the fly likes Can you please explain this output - Kind of recursion Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Can you please explain this output - Kind of recursion" Watch "Can you please explain this output - Kind of recursion" New topic
Author

Can you please explain this output - Kind of recursion

Krishna Rao
Greenhorn

Joined: Nov 15, 2006
Posts: 8
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

Joined: Oct 12, 2006
Posts: 134
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

Joined: Nov 15, 2006
Posts: 8
Thanks Dinesh. I understand that.
But it should have been 1,2,3 right ? I might be totally wrong.

Please clarify.
Joanne Neal
Rancher

Joined: Aug 05, 2005
Posts: 3429
    
  12
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


Joanne
Krishna Rao
Greenhorn

Joined: Nov 15, 2006
Posts: 8
Thanks Joanne. It clarifies.

Regards
-Krishna Rao
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Can you please explain this output - Kind of recursion
 
Similar Threads
Exception
flow control
Infinite loop in Exception ??
Exception Handling
Why is 5 getting printed here?