Strange finally behaviour?

前端 未结 7 1265
野性不改
野性不改 2020-12-03 11:12
public class Test2 {

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

        System.out.print(a);
    }


           


        
7条回答
  •  难免孤独
    2020-12-03 11:35

    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);
              }
          }
      

提交回复
热议问题