Sub topic 1
From Source File to Running Program: The JVM Pipeline
Prerequisites
Assume you can write and run basic Java programs, use javac and java, and understand classes, methods, and static members.
From source file to running program: the JVM pipeline
The Java compiler, javac, translates source code into a platform-independent class file. The JVM then loads that file, checks and prepares it, and executes its bytecode.
The same class file can run on different operating systems when compatible JVM implementations are available. The JVM hides operating-system details behind its class-file format and execution engine.
Inside a `.class` file
A class file is a binary structure, not a text version of the source. Its header includes:
- The magic number
0xCAFEBABE. - Minor and major version numbers. Java 11 class files use major version 55.
- A constant-pool count and constant-pool entries.
- Class access flags, such as public or final.
- References to the current class and its superclass.
- Field and method descriptions.
- Attributes, including method bytecode and debugging information.
You can inspect method bytecode with javap:
public class MathOps {
public static int add(int a, int b) {
return a + b;
}
}$ javac MathOps.java
$ javap -c MathOps
public static int add(int, int);
Code:
0: iload_0
1: iload_1
2: iadd
3: ireturnThe constant pool and symbolic references
The constant pool is a table inside the class file. It stores literals and symbolic descriptions of classes, fields, and methods. For example, a method reference can name a class and method without storing a direct memory address. The JVM resolves that symbolic reference when needed.
Where data lives
The heap stores objects and arrays. Metaspace stores class metadata, such as method and field descriptions. Each thread has a private thread stack. A method call creates a stack frame containing local variables, an operand stack, and bookkeeping information.
The bytecode above loads the two integer parameters onto the operand stack. iadd removes them, adds them, and puts the result back. ireturn returns that result to the caller.
Exercise
What does iload_0, iload_1, and iadd do in the add method?
Show answer
They push the first two local integer variables onto the operand stack, then replace them with their sum.