Java 101 - Stack and Heap

The JVM divided the memory into the following sections.

  • Heap
  • Stack
  • Code
  • Static

The Heap

The heap is an area where we can create and destroy objects as needed. The stack is organized and neat and it's counterpart the heap it disorganized and messy.

How do we access the heap if it's messy. We use a reference variables. When we instantiate an object, we assigned it a reference variable and that is how we access it.

In conclusion:

  • All variables are stored on the stack.
  • Objects are stored on the heap.
  • Primitive variables contain the value assigned to them ( on the stack ).
  • Reference variable contain the address of the object that it points to.

The Stack

The stack is a very organized area in the computer's memory where we store local variables. A local variable is a variable created in the currently executing code block. The variables are stored by the thread of execution, meaning from the first line to the last one.

Below is a program that stores a local variable and it's representation as it is being parsed by the JVM.

public class Stack
{
    public static void main (String [] args)
    {
    int length = 5;
    int width = 10;      int area = length * width;
    System.out.println("The area of the rectangle is " + area );
    }
}

The JVM will parse it the following way.

Stack

  • length = 5
  • width = 10
  • area = 15
  • PrgCtr

First it stores the local variables the it hits “System.out.print” and then it exits the stack and the class.