Search code examples
javatry-catchtry-catch-finally

How try...finally works internally


Currently I am working on code optimization where I am using try.. finally block to deference my objects.

But I have confusion that how returning an object is managed when I am creating null reference to an object in my finally block. ??

While returning an object in a try block, Will it create a pre-compiled statement during compilation? or create new reference in heap while it comes to return statement? or just return a current reference of an object?

Below is my research code.

public class testingFinally{
    public static String getMessage(){
        String str = "";
        try{
            str = "Hello world";
            System.out.println("Inside Try Block");
            System.out.println("Hash code of str : "+str.hashCode());
            return str;
        }
        finally {
            System.out.println("in finally block before");
            str = null;
            System.out.println("in finally block after");
        }
    }

    public static void main(String a[]){
        String message = getMessage();
        System.out.println("Message : "+message);
        System.out.println("Hash code of message : "+message.hashCode());
    }
}

Output is:

Inside Try Block
Hash code of str : -832992604
in finally bolck before
in finally block after
Message : Hello world
Hash code of message : -832992604

I am very surprised when I see both returning object and calling object have same hashcode. So I am confused about object reference.

Please help me to clear this fundamental.


Solution

  • The method doesn't exactly return an object. It returns a reference to an object. The object that the reference refers to stays the same inside and outside the method call. Because it's the same object, the hashcode will be the same.

    The value of str at the time of return str is a reference to the String "Hello World". The return statement reads the value of str and saves it as the return value of the method.

    Then the finally block is run, which has the chance to change the return value by containing its own return statement. Changing the value of str within the finally block doesn't change the already set return value, only another return statement will.

    Because setting str to null has no effect, you can remove statements like this. It will go out of scope as soon as the method returns anyway so it doesn't help with garbage collection.