Class Loading & Bytecode: From .java to Running

Class Loading & Bytecode: From .java to Running in Java: Java's "write once, run anywhere" promise rests on a two-step process.

Concept Explanation

Java's "write once, run anywhere" promise rests on a two-step process. javac compiles your source to bytecode — instructions for an imaginary machine. The JVM on each platform then executes that bytecode.

Hello.java  --javac-->  Hello.class  --JVM-->  native instructions
 (source)               (bytecode)            (platform-specific)

The .class file is identical on Windows, Linux, and macOS. Only the JVM differs.


Looking at Bytecode

public int add(int a, int b) { return a + b; }
javap -c Calculator
public int add(int, int);
  0: iload_1        // push first argument
  1: iload_2        // push second argument
  2: iadd           // add the top two stack values
  3: ireturn        // return the result

The JVM is a stack machine — operands are pushed and popped rather than held in named registers. Reading javap output is how you settle arguments about what the compiler actually does (for example, that string concatenation in a loop creates a new object each iteration).


The Loading Sequence

A class is loaded the first time it is genuinely needed:

  1. Loading — find the .class file and read it into memory.
  2. Linking
  • Verification: check the bytecode is valid and safe.
  • Preparation: allocate static fields with default values.
  • Resolution: resolve symbolic references.
  1. Initialisation — run static initialisers and static field assignments.
public class Config {
    static { System.out.println("Config initialised"); }
    static final String NAME = "app";
}

That block runs once, at first active use — not at JVM startup. This laziness is why an expensive static initialiser makes the first request slow rather than startup.


The ClassLoader Hierarchy

Bootstrap ClassLoader     → core JDK classes (java.lang, java.util)
      ↑
Platform ClassLoader      → JDK modules beyond the core
      ↑
Application ClassLoader   → your classes and dependencies
      ↑
Custom ClassLoaders       → plugins, app servers, hot reload

Loading uses parent-first delegation: each loader asks its parent before trying itself. This is a security property — you cannot substitute your own java.lang.String, because the bootstrap loader always wins.


JIT Compilation

Bytecode starts out interpreted. The JVM counts how often each method runs, and the JIT compiler converts hot methods to native code:

  • C1 compiles quickly with modest optimisation.
  • C2 compiles slowly with aggressive optimisation — inlining, loop unrolling, escape analysis.

This is why the same loop can be ten times faster on its thousandth iteration than its first, and why microbenchmarks that skip a warm-up phase produce nonsense.

java -XX:+PrintCompilation MyApp        # watch methods get compiled

Common Mistakes

  1. Benchmarking without warm-up: You measure the interpreter, not your code. Use JMH.
  2. Expecting static blocks at startup: They run at first use, which can be much later.
  3. Mismatched class file versions: Compiling with JDK 21 and running on 17 gives UnsupportedClassVersionError. Use --release.
  4. Duplicate classes on the classpath: The first one found wins, silently. This is the source of many "impossible" NoSuchMethodErrors.

Best Practices

  • Use javap -c to answer "what does the compiler actually generate?" rather than guessing.
  • Compile with --release N so you cannot accidentally use APIs newer than your target.
  • Keep static initialisers cheap — an exception there becomes ExceptionInInitializerError, which is hard to diagnose.
  • Keep the classpath clean: One version of each library.

Practice Exercises

  1. The Disassembly: Write a method that concatenates strings in a loop, run javap -c, and identify the object created each iteration.
  2. The Lazy Static: Add a printing static block to a class and confirm it runs at first use, not at startup.
  3. The Warm-Up: Time a loop's first 1,000 and last 1,000 iterations. Explain the difference using JIT compilation.