CodeBlanks Logo Icon CodeBlanks

Heap and stack

Learn heap and stack memory regions.

Heap and stack

The JVM splits memory into two main regions. The stack is allocated per method call; local primitives and object references live here. The heap holds all objects created with new and is shared across the application.

Example: int x = 5 is on the stack; in Box b = new Box() the reference b is on the stack while the object itself is on the heap. The stack is freed when the method returns; the heap is left to the garbage collector.

Reference versus object

A variable holds a reference to an object, not the object itself. The reference is on the stack; the object is on the heap. Two variables can point to the same object.

Example: Box a = new Box(); Box b = a;. Here a and b reference the same heap object; a change a.v = 9 is also visible through b.v. Primitives instead hold their value directly on the stack; assignment copies. This distinction drives side effects and copying behavior.

Practice Use stack and heap together

Define a Box class with an int v field and a Box(int v) constructor. A static int square(int n) method returns n * n. In main, declare int x = 5, create an object with new Box(x), and print the result of square(b.v) with System.out.println.

Starter code

Main.java
// Define the Box class
// Add the square method
// Print the result in main

Sample solution

Main.java
class Box {
    int v;
    Box(int v) { this.v = v; }
}

public class MemoryDemo {
    static int square(int n) { return n * n; }
    public static void main(String[] args) {
        int x = 5;
        Box b = new Box(x);
        System.out.println(square(b.v));
    }
}

Expected output

25

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 In which memory region does an object created with new live?

  • On the stack
  • In Metaspace
  • In a register file
  • On the heap Correct answer

Explanation: Objects created with new live on the heap.

2 Complete the object creation operator

Question
Box b = ____ Box(5);
Answer
Box b = new Box(5);

Explanation: The new operator creates an object on the heap.

3 Match the memory regions

Term Meaning
Heap new objects
Stack Local variables
Metaspace Class metadata

All lessons in Expert