Originally posted by Ilja Preuss:
The "new" operator creates a new object of the ClassA type on the heap and returns a reference to the object. The reference is then assigned to the obj variable. As obj is a local variable, it lives on the stack.
Does that help?
To add, the starting point to make the distinction is the lifetime-predictability of the variable (reference).
Since, for objects, the lifetime is unpredictable, they are always in the heap.
For in-method variables (primitives and references), like Ilja explains, the lifetime is predictable, and hence in the stack.
For instance variables (primitives and references), the lifetime is unpredictable, hence the heap.
This holds for both references and primitives.
I hope this properly summarizes the concept. html
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/variables.htmljava
http://www.javaworld.com/article/2078645/java-se/jvm-performance-optimization-part-3-garbage-collection.htmlweb
http://www.dynatrace.com/en/javabook/how-garbage-collection-works.htmloracle
http://www.codeweblog.com/jvm-memory-and-garbage-collection-policy-analysis-model/jvm
http://www.journaldev.com/2856/java-jvm-memory-model-and-garbage-collection-monitoring-tuningpost
http://www.javaworld.com/article/2078645/java-se/jvm-performance-optimization-part-3-garbage-collection.htmlui
Reference Types In Java - Part 1this
http://java.dzone.com/articles/reference-types-java-part-1spa