Tuesday, July 7, 2009

Stack and Heap in java

Stack in java is used to store methods and local variables or stack variable.
It is useful in threading and exception handling. As per the behavior of stack (LIFO) Last In First Out, the elements in the stack depends on each other.

For example

 void test() { 
int a;
chain();
}

Here while running the above code, first test() method will get invoked. After that chain() will be called..now test() will be in the top of stack memory.
After the execution of chain() only, the test() will finish its execution (as per LIFO).

On the other hand Heap is mainly used to store Objects. Whatever objects (instance variables) that is created is stored in Heap only.

No comments: