I am creating a String object within createString() function and returning a reference to it. When i print the hashCode of object created within createString and the one that is returned to the main method, the reference points to the same object. My question is -
Object created within function stack of createString() is out of scope within main method, so why is it accessible from the main method?
import java.util.*;
public class Temp {
public static void main(String[] args) {
Temp temp = new Temp().createString();
System.out.println(Integer.toHexString(System.identityHashCode(temp)));
}
public final Temp createString() {
Temp strs = new Temp();
System.out.println(" string identity: " + Integer.toHexString(System.identityHashCode(strs)));
return strs;
}
}