0

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;
    }
}
Jimm
  • 8,165
  • 16
  • 69
  • 118
  • String will return by value and it returns a copy of the reference – Mohsen Dec 06 '18 at 20:57
  • 1
    Why are you creating a new `Temp` and returning it in `createString`? The original form of the question created a `String` and returned it. – rgettman Dec 06 '18 at 21:01
  • I changed the code to return Temp to eliminate String intern issue – Jimm Dec 06 '18 at 21:03
  • javadoc of `Object`s hash code (`identityHashCode` points to that): "It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results.... typically implemented by converting the internal address of the object into an integer, but this ... is not required" - so it is not (always) reliable. By returning the instance it is (obviously?) the same instance before being returned. Out of scope - not sure what you meant by that - both methods are inside of `Temp`. – user85421 Dec 06 '18 at 21:32
  • BTW, to create a non-interned string just use `new String("...")` – user85421 Dec 06 '18 at 21:38

1 Answers1

2

The simple answer is that you are creating an object (on the heap) in createString, and returning it to main. Because it is on the heap, and because main now has a reference to it, it is still a valid, viable String/Object

In terms of scoping rules, these apply only at compile time, and only to the user defined label names of the variables, not to the data/content that they hold.

ControlAltDel
  • 33,923
  • 10
  • 53
  • 80
  • The objects within function should be created on function stack and not global heap – Jimm Dec 06 '18 at 21:04
  • @Jimm "Whenever we create any object, it’s always created in the Heap space. " https://www.journaldev.com/4098/java-heap-space-vs-stack-memory – ControlAltDel Dec 06 '18 at 21:07
  • @Jimm objects are always on the heap; local variables which refer to them are on the stack. – Andy Turner Dec 06 '18 at 21:14