Strange finally behaviour?

前端 未结 7 1259
野性不改
野性不改 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:50

    return returns value not reference. When return q; gets executed in catch current value of q reference is cached by method as its result. So even if in finally block you will reassign q with new value it doesn't affect value already cached by method.

    If you want to update value which should be returned you will have to use another return in your finally block like

    } finally {
        q = "hello";
        System.out.println("finally value of q is " + q);
    
        return q;//here you set other value in return
    }
    

    Other way of affecting returned value is by changing state of cached object. For instance if q was a List we could add new element to it (but notice that changing state is not the same as reassigning a new instance, just like we can change state of final variable, but we can't reassign it).

    } finally {
        q.add(new Element); //this will place new element (update) in List 
        //object stored by return because it is same object from q reference
        System.out.println("finally value of q is " + q);
    }
    

提交回复
热议问题