Sub topic 2
Frames, Locals, Invocation, and Class Loading
Assume you can compile and run basic Java programs and understand classes, methods, static, and exceptions. This chapter connects bytecode instructions to the JVM structures that execute them.
Frames, locals, and the operand stack
A stack frame is the JVM's workspace for one method call. Each frame contains:
- A local-variable array for parameters and method variables.
- An operand stack for intermediate values.
- A reference to the runtime constant pool for the current class.
For instance methods, local variable slot 0 usually contains this. For a static method, slot 0 contains the first parameter.
public class MathOps {
public static int add(int a, int b) {
return a + b;
}
}Compile and inspect it:
$ javac MathOps.java
$ javap -c MathOps
public static int add(int, int);
Code:
0: iload_0
1: iload_1
2: iadd
3: ireturniload_0 pushes local variable a onto the operand stack. iload_1 pushes b. iadd removes both values, adds them, and pushes the result. ireturn returns the integer at the top of the stack. The JVM creates a new frame for each active method call and removes it when the method returns.
How methods are invoked
The invocation instruction determines how the target method is found:
invokestaticcalls a static method.invokevirtualselects an overridden instance method at runtime.invokeinterfaceperforms a similar lookup through an interface.invokespecialhandles constructors, private methods, and selected superclass calls.invokedynamicsupports runtime linkage, including lambda expressions.
Arguments are placed on the caller's operand stack. The JVM transfers them into the new frame's local variables.
The class loading lifecycle
Before executing a class, the JVM generally performs these phases:
- Loading obtains the class bytes and creates a
Classobject. - Linking verifies bytecode, prepares static fields with default values, and resolves symbolic references as needed.
- Initialization runs static field initializers and static initializer blocks in textual order.
Class loaders and parent delegation
Java 11 commonly uses this hierarchy:
- The bootstrap loader loads core classes such as
String. ItsgetClassLoader()result isnull. - The platform loader loads platform modules.
- The application loader loads classes from the application class path.
With parent delegation, a loader asks its parent to load a class first. It defines the class itself only if the parent cannot find it. This protects core classes from replacement and makes class identity predictable.
Exercise
Which instruction invokes a static method, and which local-variable slot usually holds this?
Show answer
invokestatic invokes a static method. Slot 0 usually holds this in an instance method.