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!
First of all:
This means an
Integerobject is created, outboxed (the JVM returns itsintValue) and100assigned to anintprimitive. TheIntegerobject is no longer referenced and can be disposed (of course maybe the JIT can optimize that toint 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.
An int variable is declared in the stack and assigned a value
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.