Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String returns in finally and try block [duplicate]

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?

like image 691
Vikas Avatar asked Nov 27 '22 14:11

Vikas


1 Answers

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.

like image 192
Neel Patel Avatar answered Nov 29 '22 04:11

Neel Patel