JVM Memory Management: Primitive and Object Swapping Mechanisms

Primitive Data Type Swapping

Consider this Java code example and its behavior:

public static void main(String[] args) {
    int first = 10, second = 20;
    swapValues(first, second);
    System.out.println("first=" + first + ", second=" + second);
}

private static void swapValues(int x, int y) {
    int temporary = x;
    x = y;
    y = temporary;
}

The output demonstrates that values remain unchanged:

first=10, second=20

JVM Runtime Architecture

Key memory areas include:

  • Thread-private regions:
    • Program Counter Register
    • Virtual Machine Stack
    • Native Method Stack
  • Thread-shared regions:
    • Method Area (Metaspace in JDK 1.8+)
    • Heap Memory

The Virtual Machine Stack stores stack frames for each method invocation. Each frame contains:

  • Local variable table
  • Operand stack
  • Dynamic linking
  • Method return information

Local variables store:

  • Primitive values
  • Object references
  • Return addresses

When main() executes, its stack frame contains args, first, and second. The swapValues() call creates a new frame with copied parameters. Changes within swapValues() affect only its local frame and don't propagate back to the caller.

Wrapper Class Swapping

Using Integer objects exhibits similar behavior:

public static void main(String[] args) {
    Integer numA = 100, numB = 200;
    swapWrappers(numA, numB);
    System.out.println("numA=" + numA + ", numB=" + numB);
}

private static void swapWrappers(Integer x, Integer y) {
    Integer tmp = x;
    x = y;
    y = tmp;
}

Output remains unchanged:

numA=100, numB=200

While local variables now store references to heap objects, the swapping mechanism only modifies reference copies within the swapWrappers() frame. The original references in main() remain unaffected.

String and Object Swapping

This behavior extends to other object types:

public static void main(String[] args) {
    CustomEntity obj1 = new CustomEntity("Data1");
    CustomEntity obj2 = new CustomEntity("Data2");
    swapEntities(obj1, obj2);
    System.out.println("obj1=" + obj1 + ", obj2=" + obj2);
}

private static void swapEntities(CustomEntity e1, CustomEntity e2) {
    CustomEntity temp = e1;
    e1 = e2;
    e2 = temp;
}

Output confirms the pattern:

obj1=Data1, obj2=Data2

Summary

Primitive swaps fail because:

  • Method praameters are value-copied to new stack frames
  • Changes don't propagate back to caller frames

Object swaps fail because:

  • Reference copies are modified, not original references
  • Heap objects remain unmodiifed

Tags: java JVM Memory Management Stack Frame Primitives

Posted on Sun, 28 Jun 2026 17:39:22 +0000 by chomedey