Why does changing the returned variable in a final

2019-01-01 12:52发布

I have a simple Java class as shown below:

public class Test {

    private String s;

    public String foo() {
        try {
            s = "dev";
            return s;
        } 
        finally {
            s = "override variable s";
            System.out.println("Entry in finally Block");  
        }
    }

    public static void main(String[] xyz) {
        Test obj = new Test();
        System.out.println(obj.foo());
    }
}

And the output of this code is this:

Entry in finally Block
dev  

Why is s not overridden in the finally block, yet control printed output?

7条回答
栀子花@的思念
2楼-- · 2019-01-01 13:15

There are 2 things noteworthy here:

  • Strings are immutable. When you set s to "override variable s", you set s to refer to the inlined String, not altering the inherent char buffer of the s object to change to "override variable s".
  • You put a reference to the s on the stack to return to the calling code. Afterwards (when the finally block runs), altering the reference should not do anything for the return value already on the stack.
查看更多
登录 后发表回答