Header Ads

How Memory Allocation Happens in Java?

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.

A quick way to explain java memory allocation is , java mainly keeps it data to heap and stack area. So whenever JVM gets some memory it divides the area to stack and heap area.
Heap area is to keep the live objects and stack area is to keep all method calls and local variables.
Mainly the heap area is the garbage collectable area.

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
Local variables mostly declared in methods, even the method parameters are local to method. As all the methods stay in stack, hence local variables stay in stack in the frame corresponding to the method. That is the reason Local variables are called stack variables.

again for instance variable they are mostly declared inside a class. They become active when the object is created. So instance variable stay in heap area,where the objects are stored.The memory allocation depends on the size of the type. say a int will take 32 bits, a long will take 64 bits. JVM will not consider the value of it, It will allocate 32 / 64 bit memory.

For methods as I said earlier, JVM pushes themselves to stack.
So if your program have 3 methods
dosometask1() // having 1 local variable
dosometask2()//having 2 local variables

JVM reads it and pushes the methods to the stack one by one.
so the stack will be ..
  • dosometask2()
  • dosometask1()
  • main()
with Local variables.
One more area we need to think, if the variable holds reference of an object. like..
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)
Powered by Blogger.