DEV Community

Adetayo Akinsanya
Adetayo Akinsanya

Posted on Originally published at unkletayo.dev on

What happens when you run a Java program?

What happens when you run a Java program?

You type javac Hello.java. A moment later, Hello.class appears. Then java Hello, and something prints to the terminal. Those two commands do very different things, and understanding exactly what each one does is the foundation everything else in Java builds on.

Here is the program we'll trace all the way through.

// Hello.java
public class Hello {
    public static void main(String[] args) {
        System.out.println("Hello");
    }
}

Enter fullscreen mode Exit fullscreen mode

Three documents, not one

Before anything else, it helps to know that "Java" is actually three separate specifications that meet at a file boundary.

The Java Language Specification defines what valid Java source code means. It says what int x = 5 means, what instanceof does, how method overloading is resolved. It says nothing about .class files or how programs execute.

The Java Virtual Machine Specification defines an abstract stack-based machine that processes a specific binary instruction set called bytecode. It says nothing about .java files. It doesn't know what source code is.

HotSpot is a concrete program, one real implementation of the JVMS abstract machine. When someone says "Java compiles to native code" or "Java is interpreted", they're describing HotSpot's behaviour, not anything the JVMS requires. A conforming JVM could interpret every instruction forever and still be correct.

javac translates source code (JLS) into bytecode (JVMS). java runs a JVM (HotSpot) that executes the bytecode. This three-way separation explains a lot of "why does Java do that?" questions later in this series.

What javac does

javac does more than translate text. It parses the source, builds an abstract syntax tree, type-checks every expression against the JLS rules, and then emits bytecode. The resulting .class file contains the compiled bytecode for every method, plus a constant pool, a lookup table of strings, class names, method signatures, and other constants the methods refer to by index.

You can inspect the result yourself:

javac Hello.java
javap -c Hello.class

Enter fullscreen mode Exit fullscreen mode

The javap tool ships with the JDK and disassembles .class files. The output for Hello.class looks like this (expected output from OpenJDK 25, your offsets will match):

Compiled from "Hello.java"
public class Hello {
  public Hello();
    Code:
       0: aload_0
       1: invokespecial #1 // Method java/lang/Object."<init>":()V
       4: return

  public static void main(java.lang.String[]);
    Code:
       0: getstatic #7 // Field java/lang/System.out:Ljava/io/PrintStream;
       3: ldc #13 // String Hello
       5: invokevirtual #15 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
       8: return
}

Enter fullscreen mode Exit fullscreen mode

The numbers on the left are bytecode offsets in bytes, not line numbers. This is a stack machine. Instructions push values onto an operand stack and pop them off. Each method has its own operand stack and its own set of local variable slots.

Walk through main instruction by instruction:

  • getstatic #7: push the value of System.out (a PrintStream object reference) onto the operand stack. The #7 is an index into the constant pool; at runtime the JVM resolves it to the actual field value.
  • ldc #13: push the string constant "Hello" onto the operand stack.
  • invokevirtual #15: call println. The JVM pops the PrintStream reference and the string off the stack, dispatches the call, and the method runs.
  • return: exit main.

The bytecode for Hello() (the constructor the compiler generated automatically) loads this with aload_0, calls Object.<init> to initialise the parent, and returns.

This is what your Java source actually becomes. The JVM executes these instructions, not your original text.

What java does: loading and linking

java Hello starts a JVM process, which then has to get the Hello class ready before it can run anything. This happens in three stages.

Loading is finding and reading the bytes. The JVM uses a chain of class loaders. The bootstrap class loader (built into the JVM, not a Java class itself) loads java.lang.*, java.io.*, and other platform classes from the JDK's own modules. The platform class loader (formerly extension class loader) handles extension modules. The application class loader loads your .class files from the classpath. When Hello references java.lang.System, the JVM loads System if it isn't already loaded. A class doesn't exist in the JVM until it has been loaded. Referencing a class name in source code is not the same as having the class available at runtime.

Linking has three sub-stages. Verification checks that the bytecode is well-formed. Instructions are valid, type constraints are respected, and there are no stack underflows. Preparation allocates memory for static fields and sets them to default values (0 for numeric types, false for boolean, null for references). Resolution replaces symbolic references in the constant pool with direct references to runtime representations. The #7 index pointing to System.out gets resolved to an actual memory location.

Initialisation runs the class's static initialiser (the <clinit> method, if any). For Hello there's nothing to initialise. For a class with static int COUNT = 100;, that assignment runs here. Static fields reach their declared values during initialisation, not during preparation (preparation only sets the default).

The JVM performs this sequence lazily. A class is loaded the first time something needs it, not when the program starts. That means a class with a syntax error in an unreachable branch won't necessarily cause problems until that branch is first reached.

Execution: interpreter, then JIT

Once Hello is initialised, the JVM calls main. The initial execution mode is interpretation. The JVM has an interpreter that reads each bytecode instruction and carries it out directly, in a loop that processes one instruction per iteration.

Interpretation is flexible but slow compared to native code. HotSpot watches how often each method is called. When a method becomes "hot", meaning it has been called often enough to cross a threshold, HotSpot's JIT compiler kicks in. It compiles the bytecode for that method into native machine instructions for your actual CPU. After that, calling the method runs the native code directly, skipping the interpreter entirely.

HotSpot has two JIT compilers. C1 (the client compiler) is fast to compile and produces moderately optimised code. It's used early for methods that are warm but not yet very hot. C2 (the server compiler) takes longer to compile but produces highly optimised native code, applying techniques like inlining, loop unrolling, and escape analysis. The same Java method can be compiled by C1 first, then recompiled by C2 as it stays hot.

None of this is visible to you as the programmer. The JVM decides which methods to compile, when to compile them, and whether to deoptimise and recompile if its assumptions turn out to be wrong. From the JLS's perspective, what happens at runtime is entirely the JVM's business.

One JIT optimisation worth knowing early: escape analysis. If the JVM can prove that an object never escapes the method that creates it, it can allocate the object on the stack frame instead of the heap. This means no garbage collector involvement and faster allocation. HotSpot does this in practice. That's why "Java objects always live on the heap" is a statement about typical HotSpot behaviour, not a JVMS guarantee.

The call stack

Each thread in a Java program has its own call stack. The stack is a sequence of frames. When main calls add(3, 4), a new frame is pushed. When add returns, its frame is popped. The return value lands on the caller's operand stack.

Each frame holds:

  • Local variables : numbered slots. Slot 0 in an instance method holds this; in a static method slots start from the first parameter. a and b in add(int a, int b) are slots 0 and 1.
  • Operand stack : the working area for the current instruction sequence.
  • A reference to the runtime constant pool of the current class, so symbolic references can be resolved.

Trace it concretely. The JVM starts executing main. The main frame is on the stack. main computes int result = add(3, 4):

  1. The JVM pushes an add frame onto the stack. Slot 0 of the new frame gets the value 3; slot 1 gets 4. These are copies of the arguments, not the original storage.
  2. Inside add, the bytecode loads slot 0 (iload_0), loads slot 1 (iload_1), executes iadd, and returns the result with ireturn.
  3. The add frame is popped. The return value 7 is pushed onto main's operand stack. main stores it in its local variable for result.

The stack is bounded in size. If you write a method that calls itself without ever reaching a base case, the JVM keeps pushing frames until it runs out of stack space. The result is a StackOverflowError. This isn't specific to recursive methods. A chain of a thousand non-recursive method calls deep enough would have the same effect, just far less likely in practice.

Prediction exercise

Before running: what do you expect javap -c to show for the following program?

public class Add {
    public static void main(String[] args) {
        int a = 3;
        int b = 4;
        int c = a + b;
        System.out.println(c);
    }
}

Enter fullscreen mode Exit fullscreen mode

Specifically, how many bytecode instructions appear between the start of main and the invokevirtual for println? And which instructions handle the local variables a, b, and c?

Compile it, run javap -c Add.class, and check. The instructions you see, iconst_3, istore_1, iload_1, iadd, and so on, reveal how the JVM's stack-based architecture handles local variables and arithmetic. Each instruction's name encodes its type (i for int, a for reference) and what it does. Once you can read a few lines of bytecode, the JVM's execution model stops being abstract.

Top comments (0)