Strange finally behaviour?

2019-01-07 21:42发布

public class Test2 {

    public static void main(String[] args) {
        Test2 obj=new Test2();
        String a=obj.go();

        System.out.print(a);
    }


    public String go() {
        String q="hii";
        try {
            return q;
        }
        finally {
            q="hello";
            System.out.println("finally value of q is "+q);
        }
    }

Why is this printing hii after returning from the function go(), the value has changed to "hello" in the finally block?

the output of the program is

finally value of q is hello
hii

标签: java finally
7条回答
We Are One
2楼-- · 2019-01-07 22:08

Try using StringBuffer instead of String and you will see the change .... it seems the return statement blocks the object which is to be returned and not the reference. You could also try to verify this by printing the hashcode of :

  • object being returned from go()
  • object in finally
  • object being printed from main()

    public static void main(String[] args){

        Test obj=new Test();
            StringBuffer a=obj.go();
            System.out.print(a);
        }
      public StringBuffer go() {
            StringBuffer q=new StringBuffer("hii");
            try {
                return q;
            }
            finally {
                q=q.append("hello");
                System.out.println("finally value of q is "+q);
            }
        }
    
查看更多
登录 后发表回答