Memory Allocation to Object and Methods Stack and Heap in Java

This class discusses Memory Allocation to Object and Methods Stack and Heap in Java.

The reader should have prior knowledge of the class and object. Click Here.

Random Access Memory:

The below diagram shows the random access memory organization we are using.

The RAM contains 8 bits in each line.

The line numbers are addressed from zero.

The Java virtual machine will allocate stack and heap space for execution.

We understand the stack and heap space allocation during execution.

Example:

The below diagram shows the example program.

The program is discussed in our previous class.

The class “firstExample” has one instance variable and two methods.

The class test has the main method.

The execution starts from the main method.

To execute the main method, we need some space.

The variables present in the main method need some space.

Before executing the main method, space is allocated in the stack for variables.

How much space is allocated for the main method?

The main method has an integer variable and an object variable.

Both variables need 8 bytes of space.

So eight lines are allocated to the main method in the stack.

The below diagram shows the stack space.

The memory location 2000 to 5000 is allocated for the stack.

The main method allocated space from 2000 to 2007.

In the main method, we create an object for the class “firstExample”.

The class “firstExample” has one instance variable.

After creating an object, memory is allocated to the object.

The memory for the object is allocated in the heap.

The memory location 5001 to 5004 is allocated for an object ob.

The below diagram shows the heap space.

The next line of code calls the “add” method.

The add method is assigned space in the stack.

The add method has three variables a,b, and c.

So “add” method allocated 12 bytes of space to store the three variables in the stack.

The add method assigned space from 2008 to 2019 in the stack.

After completing add method, the space allocated for add will be removed.

That is the reason variables in the method are local.

The local variables can be used during the method execution.

After completion of method execution, local variables are no more.

Now the execution moves to the main method and calls the multiplication method.

The multiplication method contains three variables.

So the space from 2008 to 2019 was allocated to the multiplication method.

 In the above way, memory is allocated for methods and objects in Java.