Search code examples
javaheap-memoryinstantiation

Java primitive object instanciation: heap or not?


So I was reading this book where it says that if I create a class Point and then instantiate it by doing Point p1 = new Point(); then I will have:

  • a Point object on the heap (as a result of the "new" keyword);
  • a reference to this object (p1);
  • and when an object has no references then it can be disposed by the garbage collector.

I guess I got the meaning, but it got me thinking. What happens "memory-wise" with primitive types and strings, i.e. what is the difference between:

 - int x1 = 100;
 - String s1 = "hello";

and

 - int x2 = new Integer(100);
 - String s2 = new String("hello");

In the first case, are '100' and 'hello' going to be instantiated and stored on the heap? Else, what are x1 and s1 referencing?

Thank you!


Solution

  • First of all:

     int x2 = new Integer(100);
    

    This means an Integer object is created, outboxed (the JVM returns its intValue) and 100 assigned to an int primitive. The Integer object is no longer referenced and can be disposed (of course maybe the JIT can optimize that to int x2 = 100).

    I assume you are talking about local variables, because attributes are part of the object and so lie with it in the heap.

     int x1 = 100;
    

    An int variable is declared in the stack and assigned a value

     String s1 = "Hello";
    

    An String object is created (or referenced, see String.intern()) and a pointer is added to the stack.

    The other possibilities are exactly the same.