i am sought of confused regarding stack and heap variables.
when i say Object o=new Object inside a method, the variable o is placed in the stack and an Object is created in the heap and its address is assigned to o. When we define an Object as an instance variable where is that placed meaning ...
where is Object o now placed, in the stack or the heap ?.
This is what i understand happens: first variable myObj is added to the stack then a new object XYZ is added to the heap. This latter part means that space is allocated for all of the objects member variables, which includes your Object o member. As this member is a reference variable too, it will point to an object (instance of Object) which would be created on the heap as well.
Afzal Rehman wrote:Thanks sir,
but how any reference it would help me to more clear this concepts
Google for "escape analysis". Basically, it is a concept related to performance. If the JVM determines that an object can't escape a method -- created in the method, throw away in the method, nothing else in the method (or class being instantiated) that can cause a reference to leave the method -- then it has the option of instantiating it on the stack. Upon completion, the object is just finalized. There is no need to GC the object, as the memory will simply be reclaimed upon return.