Forwarded from http://www.javatutorialhub.com/wiki/Stack_and_Heap
Stack and Heap
The JVM divided the memory into following sections.
- Heap
- Stack
- Code
- Static
This division of memory is required for its effective management.
The code section contains your bytecode.
The Stack section of memory contains methods, local variables and reference variables.
The Heap section contains Objects (may also contain reference variables).
The Static section contains Static data/methods.
Of all of the above 4 sections, you need to understand the allocation of memory in Stack & Heap the most, since it will affect your programming efforts
difference between instance variables and local variables
Instance variables are declared inside a class but not inside a method
class Student{
int num; // num is instance variable
public void showData{}
Local variables are declared inside a method including method arguments.
public void sum(int a){
int x = int a + 3;
// a , x are local variables
}
the following video demonstrates how memory is allocated in stack & heap.
Please be patient . Video will load in some time. If you still face issue viewing video clickhere
Points to Remember:
- When a method is called , a frame is created on the top of stack.
- Once a method has completed execution , flow of control returns to the calling method and its corresponding stack frame is flushed.
- Local variables are created in the stack
- Instance variables are created in the heap & are part of the object they belong to.
- Reference variables are created in the stack.
Point to Ponder:
What if Object has a reference as its instance variable?
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.