Tuesday, October 28, 2008

Heap n Stack

To explain the answer to my earlier post - "Simple One But...", first the difference between two memory areas in Java - heap and stack has to be understood.

Whenever a program runs in JVM, different ways the memory is managed is depicted in the figure below.

Now coming back to the earlier question, so whenever a methos is executed, it creates a new data record on Stack. So each instance of method call has a exclusive data record associated with it. (Figure 2) . And when a method calls other methods, records of the called methods are stacked up along with the caller. (Figure 3).

This explains or answers for the below, as static methods would be no different from non-static methods, but there is a catch here. This statement is correct only if the arguments are primitives, but when they are objects, the objects would still reside on Heap and are referred from within the stack. (Figure 4)
So finally remembering where a particular element lives, heap or stack:: a local variable (primitive or reference) belongs to a method and lives with it on a stack, while instance variable belongs to an object lives with it on a heap. Also note that a local reference variable on a stack will still be pointing to object in the heap. This object will not die with the local reference variable or post method execution.

Note: figures displayed are extracted from book (in Google Book Search) - SCJP Exam for J2SE 5 by Paul Sanghera and from lecture slides of Gerald Weber.

1 comment:

  1. that was realy informative i was just brushing with ooad