Sunday 16 December 2012

How java programs store in Heap and Stack.

Stack values are stored within the scope of the function. Once they are returned they are discarded.
JAVA only creates primitives on stack.Objects are created on heap memory.

Stack section contains methods local variables and reference variables.
Heap section contains objects.
Static section contains static data/methods.

public static void main(String args[]){
 
A parent = new A();
 
//more code
 
}
 
class A{
 
B child = new B();
 
int e;
 
//more code
 
}
 
class B{
 
int c;
 
int d;
 
//more code
 
}
 
In this case , the reference variable “child” will be created in heap ,which in turn will be pointing to its object, something like the diagram shown below.
 
 

No comments:

Post a Comment