This post is all about a small introduction about how memory is allocated in java.
When JVM is getting started , Underlaying Operating system allocates a chunk of memory to JVM.
This chunk size is dependent on the version of OS, Version of java and total memory available to OS.
So whenever JVM gets some memory it divides the area into the below four parts:
JVM divides the memory into four main sections:
- Heap area
- Stack area
- Code area
- Static area
A quick way to explain java memory allocation is , java mainly keeps it data to heap and stack area.
Heap Area/Memory:
Heap area is to keep the live objects and may contain reference variables.Instance variables are created in the heap.Mainly the heap area is the garbage collect able area.
Stack Area/Memory:
Stack area is to keep all methods and local variables and reference variables. Stack memory is always referenced in Last in First out order. Local variables are created in stack.
Code Area:
Code area is to store the actual code that will be executed as part of the program. It contains the bytecode.
Static:
This section contains the static data,method and blocks.
The problem arises when we talk about the variables. It is bit complicated to understand where they live.
Let me explain the variable part to make it easy…
Variables can be divided into two broad categories..
- Instance variables
- Local variables
main()
dosometask1() // having 1 local variable
dosometask2()//having 2 local variables
- dosometask2()
- dosometask1()
- main()
public int calc()
{
Tree t=new Tree();
}
For this case, the method calc() will go to stack, with the variable ‘t’. But since we have created a new object here with new keyword, the object will go to heap and the reference will be created with this variable.
So if only give
public int calc()
{
Tree t;
}
so public method calc will be pushed to stack with a reference variable t but no object will be crated in the heap.again when JVM gets a command called new Tree(); only then the object in the heap will be created.
In the first look we might think that object creation is calling a method..Method name is Tree()
public int calc()
{
Tree t=new Tree();
}
Not exactly, It is calling the Tree constructor.(Constructor is nothing but a set of codes which runs when we instantiate an object)