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.