I came across this question and I am unable to understand the reason of the output it is giving.
The program is:
public static String method(){
String s = new String();
try
{
s = "return value from try block";
return s;
}
catch (Exception e)
{
s = s + "return value from catch block";
return s;
}
finally
{
s = s + "return value from finally block";
}
}
The output is:
return value from try block
Now, I debugged it and the value of s
at return s
statement in try
block was return value from try block
, return value from catch block
after it returned from finally block
.
Still the output is :
return value from try block
Can any one please explain this behavior?
First of all, let us understand how Java handles method calls. There is separate stack memory for every thread. When we call any method, Java internally inserts a record at top of the stack. The record contains some details like parameters & object etc.
Here one interesting field is there: the return value. Whenever the return statement is encountered, the field is updated. Now observe the code.
In the try
block, the return value field is set to the return value from the try
block. Now as per the execution sequence the finally
block is executed. Now the finally
block modifies the string reference s
. It didn't modify the return value
field which is previously settled by try block. Finally the method call completed & Java internally pop the record & return the return value field. So it returns the return value from the try block.
If the finally
block return the string after modification, then the return value field is updated again and the updated string will be returned.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With