Java Programming, JVM Internals · December 2, 2026

Java for Beginners, Lesson 4: JVM Architecture and JIT Compilation

Java for Beginners · Module 1: Getting Started


🎯 Why Look Inside the JVM?

Think of a restaurant. The receptionist checks bookings and brings in guests (loading classes). The kitchen shelves and counters store ingredients and work in progress (memory). The chefs actually cook (execution engine). You can enjoy the meal without knowing the kitchen, but knowing it helps you understand mistakes, slow programs and strange errors like StackOverflowError.

📌 The JVM has three main parts: the Class Loader Subsystem, the Runtime Data Areas (memory) and the Execution Engine. This lesson explains each in simple words.

1️⃣ The Big Picture

Class Loader Subsystem
loads .class files, verifies them, prepares them
⬇
Runtime Data Areas (memory)
Method Area
class info, constants, static data
Heap
all objects and arrays
Java Stacks
one per thread: method calls, local variables
PC Registers
current instruction of each thread
Native Method Stacks
for code written in C/C++
⬇
Execution Engine
Interpreter · JIT compiler · Garbage Collector
⬇ calls into the operating system and native libraries (JNI)
Operating System and Hardware

Figure 1: The main parts of the JVM.

2️⃣ Class Loader Subsystem: Bringing Classes In

A class is loaded only when the program first needs it, not all at the start. Loading happens in three stages.

  • Loading: read the .class file into memory.
  • Linking: verify the bytecode is valid and safe, prepare memory for static variables, and resolve references to other classes.
  • Initialization: run static initializers and give static variables their values.
Bootstrap loader
loads core classes such as String and Object
⬇ parent of
Platform loader
loads platform and extension modules
⬇ parent of
Application loader
loads YOUR classes from the class path

Figure 2: Class loaders form a chain. A loader first asks its parent.

Program 1: Who loaded which class?

public class LoaderDemo {
    public static void main(String[] args) {
        System.out.println("String class loader : " + String.class.getClassLoader());
        System.out.println("My class loader     : " + LoaderDemo.class.getClassLoader().getName());
        System.out.println("Current thread      : " + Thread.currentThread().getName());
    }
}
🖥️ Output:
String class loader : null
My class loader : app
Current thread : main
  • String is a core class, loaded by the bootstrap loader. That loader is built into the JVM, so Java shows it as null.
  • Your own class was loaded by the application loader, whose name is app.
  • Your program starts in a thread named main.

3️⃣ Runtime Data Areas: The JVM’s Memory

Memory areaHoldsShared?Typical error
HeapObjects and arraysAll threadsOutOfMemoryError
Method AreaClass data, constants, static variablesAll threadsOutOfMemoryError
Java StackMethod calls, local variablesOne per threadStackOverflowError
PC RegisterNext instructionOne per threadnone

Figure 5: JVM memory areas at a glance.

Stack and heap in action

Local variables of primitive types, like int count, live on the stack. Objects and arrays live on the heap. A variable that refers to an object only stores a reference (like an address) to it.

public class StackHeapDemo {
    public static void main(String[] args) {
        int count = 5;                 // primitive: lives on the stack
        int[] marks = {70, 80, 90};    // array object: lives on the heap
        int[] same = marks;            // second reference to the SAME array

        same[0] = 99;
        System.out.println("count    = " + count);
        System.out.println("marks[0] = " + marks[0]);
        System.out.println("same[0]  = " + same[0]);
        System.out.println("Same object? " + (marks == same));
    }
}
🖥️ Output:
count = 5
marks[0] = 99
same[0] = 99
Same object? true
Stack (main)
count
5
marks
→
same
→
➜
Heap
one int array
[ 99 | 80 | 90 ]
both references point here

Figure 3: Two references (marks and same) point to one array on the heap. Changing it through either changes both.

  • same = marks copies the reference, not the array. Both names now point to one array.
  • Changing same[0] also changes marks[0], because there is only one array.
  • marks == same compares references, and they are equal.

When the stack runs out

Each method call adds a frame to the stack. If a method keeps calling itself forever, the stack fills up and Java throws StackOverflowError.

public class DeepRecursion {
    static int depth = 0;

    static void dive() {
        depth++;
        dive();
    }

    public static void main(String[] args) {
        try {
            dive();
        } catch (StackOverflowError e) {
            System.out.println("Stack is full: StackOverflowError caught");
            System.out.println("Went deeper than 1000 calls? " + (depth > 1000));
        }
    }
}
🖥️ Output:
Stack is full: StackOverflowError caught
Went deeper than 1000 calls? true
  • dive() has no stopping condition, so it calls itself until the stack is full.
  • try and catch let the program handle the error instead of crashing. You will study this in Lesson 28.
  • We print only whether it went deeper than 1000 calls, because the exact depth changes from computer to computer.

Garbage collection

You never free memory in Java. The Garbage Collector in the execution engine finds objects that nothing refers to any more, and frees their heap space automatically. This removes a whole class of C-style bugs such as forgetting free().

4️⃣ Execution Engine and the JIT Compiler

The execution engine runs your bytecode. It has three parts: the interpreter, the JIT compiler and the garbage collector.

The interpreter starts running at once, which is why Java programs start quickly. But interpreting is slow if the same code runs many times. So the JVM watches. When a method or loop runs again and again (it becomes hot), the JIT (Just-In-Time) compiler translates it into machine code of your computer and stores it. From then on the fast version runs.

1. Interpreter
runs bytecode line by line; starts instantly
⬇ JVM counts how often each method and loop runs
2. Hot code found
a method or loop is used again and again
⬇ JIT compiler translates it
3. Machine code stored
next calls run the fast native version

Figure 4: How the JIT compiler speeds up the parts of a program that matter most.

Program 2: A loop that becomes hot

public class HotLoop {
    static long work(int n) {
        long total = 0;
        for (int i = 0; i < n; i++) {
            total += (long) i * i % 7;
        }
        return total;
    }

    public static void main(String[] args) {
        long result = 0;
        for (int round = 0; round < 200; round++) {
            result += work(100_000);
        }
        System.out.println("Result = " + result);
    }
}
🖥️ Output:
Result = 39999800
  • work is called 200 times and loops 100,000 times each, so the JVM treats it as hot.
  • You can watch the JIT with java -XX:+PrintCompilation HotLoop. Lines like the following appear (the numbers will differ on your computer):
35    6 %     3       HotLoop::work @ 4 (29 bytes)
36    7       3       HotLoop::work (29 bytes)
37    9       4       HotLoop::work (29 bytes)
  • The method name HotLoop::work shows it was compiled. The number before the bytes (3, then 4) is the optimisation level: higher means faster machine code.

⚠️ Common Confusions

Wrong ideaTruth
“Objects are stored on the stack”Objects live on the heap; only references live on the stack
“Java has no memory management”The JVM manages it with the garbage collector
“JIT compiles the whole program at start”It compiles only hot code, while the program runs
“StackOverflowError means the computer is out of memory”Only the thread’s stack is full, usually from endless recursion
“All classes load when the program starts”Classes load when first needed

❓ Frequently Asked Questions

Q1. Why does the first run feel slower than later runs of the same code?
The JIT needs time to find hot code and compile it. This is called warm-up.

Q2. Can I force garbage collection?
You can ask with System.gc(), but the JVM decides. Normally you never need it.

Q3. Where do static variables live?
Their class data lives in the Method Area (in modern JVMs called Metaspace), and objects they refer to live on the heap.

Q4. Is each thread’s stack separate?
Yes. Every thread has its own stack, so local variables are not shared between threads.

✅ Key Takeaways

  • The JVM has a class loader, memory areas and an execution engine.
  • Classes are loaded when needed: loading, linking, initialization.
  • Stack: method calls and local variables. Heap: objects and arrays.
  • Variables for objects hold references; copying a reference does not copy the object.
  • The garbage collector frees unused objects automatically.
  • The JIT compiler turns hot bytecode into fast machine code while the program runs.
🎓 Practice questions: (1) Name the three parts of the JVM. (2) What is the difference between the stack and the heap? (3) Why does String.class.getClassLoader() print null? (4) What causes StackOverflowError? (5) In your own words, what does the JIT compiler do, and why is it called “just in time”?
All 30 lessons in this series (open course page)

Module 1 · Getting Started

Module 2 · Building Blocks

Module 3 · Operators

Module 4 · Control Flow

Module 5 · Data and Methods

Module 6 · Objects and Revision