Building a Virtual Machine in Java: From Instructions to Execution
Learn how a virtual machine executes instructions in Java, manages an operand stack, tracks program state, handles control flow, and reports runtime errors. This guide explores the architecture and implementation concepts behind an educational virtual machine, with Java code examples, instruction-set design, testing strategies, and ideas for future improvements.
// TABLE OF CONTENTS+
Building a Virtual Machine in Java: From Instructions to Execution
A virtual machine is one of the most interesting systems programming projects a developer can build. It takes concepts that usually remain hidden inside programming language runtimes and turns them into components that can be designed, implemented, tested, and inspected directly. In this article, we explore how to design an educational virtual machine in Java, focusing on the execution loop, instruction set, operand stack, program counter, control flow, and runtime error handling. The goal is to understand how a sequence of instructions becomes a running program—and how a runtime keeps track of what is happening at each step. The examples use a small, hypothetical stack-based instruction set. They illustrate the architecture and implementation techniques rather than claiming to describe a particular finished implementation or the internal bytecode format of the standard Java Virtual Machine (JVM).
1. What Is a Virtual Machine?
A virtual machine (VM) is a software-defined execution environment that provides an abstraction over the underlying machine or runtime. Instead of directly executing a program's instructions as native processor instructions, a virtual machine can interpret its own instruction set and maintain its own execution state. A VM typically defines a set of instructions, rules for interpreting those instructions, and a model of the state required to execute a program. Depending on its design, that state may include a program counter, operand stack, local variables, call frames, memory, and runtime metadata. Virtual machines are not all built for the same purpose. A system virtual machine provides an environment for running an entire operating system, while a language virtual machine provides an execution environment for programs written for a particular language or instruction format.
| Type | Type | Type |
|---|---|---|
| System VM | Provides a virtual computer for running an operating system. | VirtualBox |
| Language VM | Executes programs defined for a language or runtime. | Java Virtual Machine |
| Educational VM | Demonstrates instruction execution and runtime design. | A custom stack-based interpreter |
2. Why Build a Virtual Machine in Java?
Java is a practical language for building an educational virtual machine because it provides classes, collections, exceptions, and strong type checking. These features make it possible to model instructions, represent execution state, and separate the interpreter's responsibilities into understandable components. The project also connects several important computer science topics. Data structures become part of the runtime, control flow becomes a sequence of state transitions, and error handling becomes a matter of validating instructions and enforcing execution rules. For students exploring systems programming, interpreters, or language design, a small VM is an effective way to move beyond application-level code and understand how a program can be represented and executed by another program.
What you can learn from the project
- Instruction-set design: Define a small, consistent set of operations.
- Interpretation: Translate each instruction into an action.
- Data structures: Use a stack and other structures to model runtime state.
- Control flow: Implement jumps and conditional branches.
- Error handling: Detect invalid operations and malformed programs.
- Testing: Verify individual instructions and complete execution sequences.
- Architecture: Separate instruction definitions, execution logic, and program state.
3. How a Virtual Machine Executes a Program
A virtual machine needs a representation of a program and a mechanism for processing that representation. In a simple educational VM, a program can be stored as an ordered list of instructions. Each instruction specifies an operation and, where necessary, an operand such as a number or jump destination. The interpreter maintains a program counter (PC) that identifies the next instruction to execute. It reads the instruction, performs the corresponding operation, updates the execution state, and determines what should happen next. For ordinary instructions, the program counter typically advances to the following instruction. A jump instruction can replace that next position with a specified destination, while a conditional jump does so only when its condition is satisfied. Execution ends when the program reaches a defined halt instruction or another explicit termination condition.
The basic execution sequence
- Load or construct the program.
- Initialize the virtual machine's execution state.
- Read the instruction at the current program counter.
- Validate the instruction and its operands.
- Execute the operation.
- Update the stack, variables, or other runtime state.
- Update the program counter.
- Repeat until the program halts or an error occurs.
4. Designing the Instruction Set
The instruction set defines the operations that a virtual machine understands. It is effectively the contract between a program and its interpreter: a program is valid only when its instructions follow the format and rules the runtime supports. A beginner-friendly VM can start with a compact stack-based instruction set. Values are pushed onto the operand stack, operations consume those values, and results are pushed back. This makes arithmetic and execution-state changes straightforward to inspect.
| Instruction | Purpose |
|---|---|
| PUSH value | Pushes a value onto the operand stack. |
| ADD | Removes two values, adds them, and pushes the result. |
| SUB | Removes two values and subtracts the top value from the value beneath it. |
| MUL | Multiplies two values and pushes the result. |
| DIV | Divides two values, subject to the VM's division rules. |
| Displays or records the top value according to the VM's output rules. | |
| JUMP target | Transfers execution to an instruction index. |
| JUMP_IF_ZERO target | Jumps when the tested value equals zero. |
| HALT | Stops execution normally. |
Representing Instructions in Java
One way to represent instructions is with a Java class that stores an operation and its optional operand. An enum can make the set of supported operations explicit, while a separate instruction object can carry data such as a constant value or jump destination. This approach keeps the program's representation separate from the logic that executes it. It is also easier to validate than relying entirely on loosely formatted instruction strings.
enum OpCode {
PUSH,
ADD,
SUB,
MUL,
DIV,
PRINT,
JUMP,
JUMP_IF_ZERO,
HALT
}
final class Instruction {
private final OpCode opcode;
private final int operand;
Instruction(OpCode opcode, int operand) {
this.opcode = opcode;
this.operand = operand;
}
OpCode getOpcode() {
return opcode;
}
int getOperand() {
return operand;
}
}In this example, `OpCode` defines the available operations, while `Instruction` stores the operation and an integer operand. A production-quality design would usually validate which opcodes require operands and what those operands mean. For instance, `PUSH` might interpret its operand as a constant, while `JUMP` interprets it as a destination index. The representation should reflect the needs of the VM rather than attempt to reproduce the standard JVM's class-file format. The real JVM supports a much richer instruction set and runtime model.
5. The Operand Stack: Where Computation Happens
A stack-based virtual machine performs many operations using an operand stack. The stack follows the last-in, first-out (LIFO) principle: the most recently pushed value is the first one removed. For example, an addition instruction can pop two operands, add them, and push the result. The instruction does not need to know where the values originated. It only needs to enforce the stack contract and apply the arithmetic rule. In Java, a `Deque<Integer>` is a convenient structure for representing a stack of integer values. Its `push` and `pop` methods provide the basic operations required by this model.
import java.util.ArrayDeque;
import java.util.Deque;
final class OperandStack {
private final Deque<Integer> values = new ArrayDeque<>();
void push(int value) {
values.push(value);
}
int pop() {
if (values.isEmpty()) {
throw new IllegalStateException(
"Operand stack underflow"
);
}
return values.pop();
}
int peek() {
if (values.isEmpty()) {
throw new IllegalStateException(
"Operand stack is empty"
);
}
return values.peek();
}
boolean isEmpty() {
return values.isEmpty();
}
int size() {
return values.size();
}
}The stack wrapper centralizes stack behavior and provides a clear place to enforce invariants. Here, attempting to remove a value from an empty stack produces an explicit exception instead of silently continuing with invalid state. A VM may also need to define maximum stack depth, allowed value types, and how arithmetic overflow should behave. Those choices should be documented because they form part of the execution model.
Following Values Through an Addition
Consider the sequence `PUSH 7`, `PUSH 5`, `ADD`. The first instruction places `7` on the stack. The second places `5` above it. The `ADD` instruction removes both values and pushes their sum, `12`. The stack changes at every step. Observing these transitions is one of the simplest ways to debug a stack-based interpreter and confirm that each instruction follows its defined behavior.
| Instruction | Stack after execution (bottom → top) |
|---|---|
| PUSH 7 | [7] |
| PUSH 5 | [7, 5] |
| ADD | [12] |
6. The Instruction Pointer and Program State
The operand stack stores values used by instructions, but it is only one part of the VM's state. The runtime also needs to know which instruction to execute next. This position is commonly represented by an instruction pointer or program counter. For a simple VM, the program counter can be an integer index into a list of instructions. A sequential instruction advances it to the next index, while a jump instruction assigns a new destination. The interpreter must ensure that instruction access remains within the valid program range. Keeping the program counter explicit makes execution easier to inspect. A debugger or trace logger can report the current instruction index, the instruction being executed, and the state before and after the operation.
final class VMState {
private int programCounter;
private boolean halted;
int getProgramCounter() {
return programCounter;
}
void setProgramCounter(int programCounter) {
this.programCounter = programCounter;
}
boolean isHalted() {
return halted;
}
void halt() {
halted = true;
}
}This class is a deliberately small example of execution state. A fuller VM may also track local variables, call frames, the operand stack, output, execution limits, and error information. As the runtime grows, grouping this information into a coherent state model helps prevent unrelated parts of the interpreter from modifying it inconsistently.
7. Building the Fetch–Decode–Execute Loop
The operand stack stores values used by instructions, but it is only one part of the VM's state. The runtime also needs to know which instruction to execute next. This position is commonly represented by an instruction pointer or program counter. For a simple VM, the program counter can be an integer index into a list of instructions. A sequential instruction advances it to the next index, while a jump instruction assigns a new destination. The interpreter must ensure that instruction access remains within the valid program range. Keeping the program counter explicit makes execution easier to inspect. A debugger or trace logger can report the current instruction index, the instruction being executed, and the state before and after the operation.
final class VMState {
private int programCounter;
private boolean halted;
int getProgramCounter() {
return programCounter;
}
void setProgramCounter(int programCounter) {
this.programCounter = programCounter;
}
boolean isHalted() {
return halted;
}
void halt() {
halted = true;
}
}This class is a deliberately small example of execution state. A fuller VM may also track local variables, call frames, the operand stack, output, execution limits, and error information. As the runtime grows, grouping this information into a coherent state model helps prevent unrelated parts of the interpreter from modifying it inconsistently.
7. Building the Fetch–Decode–Execute Loop
The execution loop is the central mechanism of an interpreter. It repeatedly retrieves the instruction at the current program counter, determines which operation it represents, executes that operation, and updates the state. In a simple design, instruction dispatch can use a `switch` statement. Each case implements one opcode and defines how it affects the stack and program counter. It is important to define when the program counter advances: a common approach is to increment it before executing the instruction, then let jump operations replace it when necessary. The following example demonstrates the structure of a loop rather than a complete, ready-to-run VM. It assumes that the instruction and stack types have already been defined and that the program has been validated for the operations it supports.
while (!state.isHalted()) {
int pc = state.getProgramCounter();
if (pc < 0 || pc >= program.size()) {
throw new IllegalStateException(
"Program counter out of bounds: " + pc
);
}
Instruction instruction = program.get(pc);
// Default: continue with the next instruction.
state.setProgramCounter(pc + 1);
switch (instruction.getOpcode()) {
case PUSH:
stack.push(instruction.getOperand());
break;
case ADD: {
int right = stack.pop();
int left = stack.pop();
stack.push(left + right);
break;
}
case HALT:
state.halt();
break;
default:
throw new UnsupportedOperationException(
"Instruction not implemented: "
+ instruction.getOpcode()
);
}
}8. Arithmetic Operations and Operand Semantics
Arithmetic instructions look simple, but their behavior needs precise definitions. For `SUB`, the interpreter must specify which operand is subtracted from which. For `DIV`, it must decide how division by zero is handled and whether integer division truncates toward zero. For a stack-based subtraction instruction, the usual convention is to pop the right operand first and then the left operand. The result is the left operand minus the right operand. Reversing the order can produce incorrect results without causing a compile-time error, which is why small instruction-level tests are so useful. Java's primitive integer arithmetic also has defined overflow behavior. An educational VM can inherit Java's integer semantics, or it can choose a different rule, but that choice should be explicit and tested.
case SUB: {
int right = stack.pop();
int left = stack.pop();
stack.push(left - right);
break;
}If the stack contains `10` beneath `3`, executing `SUB` produces `7`, not `-7`. This convention should be consistent across the implementation, the instruction documentation, and the test suite. A useful rule is that every opcode should specify its required input values, the changes it makes to the stack, any other state it changes, and the errors it can produce. That makes the instruction set easier to reason about and maintain.
9. Control Flow: Jumps and Conditional Execution
Without control flow, a VM can only execute instructions in sequence. Jump instructions allow the program counter to move to another instruction, making it possible to represent loops, conditional branches, and more complex execution paths. An unconditional jump transfers control directly to its target. A conditional jump evaluates a condition and transfers control only if that condition is satisfied. In a stack-based design, the condition may be taken from the operand stack. Jump destinations must be validated. An invalid destination can send execution outside the program, while an incorrectly defined conditional instruction can leave values on the stack or consume values unexpectedly. These behaviors should be part of the opcode's documented contract.
case JUMP:
state.setProgramCounter(instruction.getOperand());
break;
case JUMP_IF_ZERO: {
int condition = stack.pop();
if (condition == 0) {
state.setProgramCounter(
instruction.getOperand()
);
}
break;
}This example assumes that the main loop advances the program counter before dispatching the instruction. A jump then replaces that already-advanced value with its target. If the loop uses a different update strategy, the jump implementation must be adjusted accordingly. Instruction indexes and jump targets should use one clearly documented convention. For example, this design uses zero-based instruction indexes. Choosing and consistently applying that convention prevents off-by-one errors.
Understanding a Conditional Branch
Imagine a program that pushes a value onto the stack and then executes `JUMP_IF_ZERO 4`. If the value is zero, execution continues at instruction index `4`. If it is non-zero, execution continues at the instruction immediately following the conditional jump. This is the foundation of branching. Combining conditional jumps with unconditional jumps allows an instruction sequence to represent more complex logic, including loops and if/else structures.
10. Runtime Errors and Invalid Programs
A virtual machine needs to handle invalid operations deliberately. Even if the interpreter compiles successfully, the program it executes may violate the rules of the instruction set. Common runtime errors include: 1. Stack underflow: An instruction attempts to consume more values than are available. 2. Invalid program counter:Execution tries to access an instruction outside the program. 3. Invalid jump destination: A jump targets an index that is not valid. 4. Unsupported opcode: The runtime encounters an operation it does not implement. 5. Division by zero: An arithmetic operation attempts to divide by zero. Invalid operand:An instruction receives an operand that violates its rules. A useful error message should describe what failed and, when possible, identify the instruction index and opcode. This makes the problem much easier to diagnose than a generic message that execution failed.
int pc = state.getProgramCounter();
if (pc < 0 || pc >= program.size()) {
throw new IllegalStateException(
"Invalid program counter: " + pc
);
}For a larger interpreter, it is useful to distinguish invalid input from failures that occur while executing a valid instruction. You may also introduce a custom exception type such as `VMRuntimeException` to attach the program counter, opcode, and a clear diagnostic message. Errors should be predictable and observable. The runtime should not silently replace missing values, ignore malformed instructions, or continue executing after its state has become invalid.
11. Runtime Architecture and Separation of Responsibilities
As the virtual machine grows, keeping all its logic in one large method becomes difficult to maintain. A better approach is to divide the runtime into components with clear responsibilities. The instruction representation defines what the program contains. The operand stack manages temporary values. The execution state tracks the current position and whether the VM has halted. The interpreter coordinates these components and implements the instruction semantics. For a more advanced design, program loading and validation can be separated from execution, while output handling and diagnostic reporting can be provided through dedicated interfaces. These boundaries make it easier to test components independently and add new features without rewriting the entire runtime.
| Component | Responsibility |
|---|---|
| Instruction model | Represents opcodes and their operands. |
| Operand stack | Stores temporary values consumed by instructions. |
| Execution state | Tracks the program counter and halt status. |
| Interpreter | Dispatches and executes instructions. |
| Program validator | Checks instruction structure and valid destinations where possible. |
| Diagnostics | Reports execution errors and optional trace information. |
12. Testing a Virtual Machine
Testing a virtual machine requires more than checking whether a sample program produces the expected output. Each instruction has its own rules, and mistakes in stack order, program-counter updates, or error handling can affect many programs. Start by testing individual operations. Then test short instruction sequences that combine them. Finally, test complete programs that include branching, termination, and invalid instructions. Tests should verify both successful execution and failure behavior. For example, an addition test should confirm the result and the final stack state, while a stack-underflow test should confirm that the VM reports an appropriate error rather than continuing with corrupted state.
Suggested test cases
- Pushing a value places it on the stack.
- Addition consumes two operands and pushes one result.
- Subtraction follows the documented operand order.
- Arithmetic instructions detect stack underflow.
- Division follows the VM's documented division-by-zero rule.
- Conditional jumps behave correctly for both true and false conditions.
- Jump instructions reject invalid destinations.
- HALT stops execution.
- An unsupported instruction produces a useful error.
- A program ending without a valid termination condition follows a clearly defined policy.
- Error messages include useful execution context where available.
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.Test;
class OperandStackTest {
@Test
void popReturnsTheMostRecentlyPushedValue() {
OperandStack stack = new OperandStack();
stack.push(7);
stack.push(5);
assertEquals(5, stack.pop());
assertEquals(7, stack.pop());
assertEquals(0, stack.size());
}
@Test
void popOnEmptyStackThrowsAnException() {
OperandStack stack = new OperandStack();
assertThrows(
IllegalStateException.class,
stack::pop
);
}
}This example uses JUnit 5 and assumes the `OperandStack` class is available to the test source set. Unit tests for the interpreter can follow the same pattern, constructing short programs and checking the resulting state or expected exceptions. The most useful tests are those that capture the VM's rules explicitly. They act as executable documentation and make it safer to extend the instruction set later. Do not claim a particular test suite passes until it has actually been run against the project.
13. Performance Considerations
A small interpreter is primarily a learning tool, so correctness and clarity should come before optimization. Nevertheless, its architecture provides a useful starting point for thinking about runtime performance. A `switch` statement is a straightforward way to dispatch instructions. The overhead of collections, object allocation, input parsing, and diagnostic logging may also affect performance, depending on how the VM is designed. None of these factors should be optimized based on intuition alone. Measure the runtime with representative programs before changing its design. A benchmark should distinguish the cost of loading or parsing a program from the cost of executing it, and should avoid drawing conclusions from a single run.
Practical performance improvements to investigate
- Avoid repeatedly parsing the same instruction representation.
- Keep the execution loop simple and predictable.
- Use data structures suited to the operations the VM performs.
- Make verbose tracing optional.
- Avoid unnecessary allocations in frequently executed paths.
- Benchmark changes against a known baseline.
- Preserve the same instruction semantics when optimizing.
14. Limitations of an Educational Virtual Machine
An educational VM deliberately simplifies many concerns that arise in production runtimes. A minimal stack-based interpreter may support only integer values, a handful of arithmetic operations, basic jumps, and a single execution context. A production language runtime may need to support methods, call stacks, object allocation, type checking, exception propagation, memory management, debugging interfaces, and carefully specified compatibility rules. The standard JVM additionally executes Java class files and implements a much broader runtime model than the illustrative VM in this article. Understanding these limitations is important. A custom VM written in Java is not automatically compatible with the standard JVM, and executing a custom instruction list is not the same as loading and running compiled `.class` files.
| Educational VM | Standard JVM |
|---|---|
| Small, custom instruction set | Defined class-file and bytecode model |
| Limited runtime state | Methods, objects, and runtime services |
| Designed for learning and experimentation | Designed to run Java bytecode implementations |
| Easy to inspect instruction by instruction | Includes extensive verification and runtime behavior |
15. Extending the Virtual Machine
Once the basic execution model is stable, the VM can be extended in stages. Each extension should add a clearly defined capability while preserving the behavior of existing instructions. Local variables are a natural next step because they introduce named or indexed storage beyond the operand stack. Call instructions and call frames can then support reusable functions. More advanced projects can introduce a parser for a textual assembly language, typed values, richer error reporting, or a debugger that displays the current instruction and stack contents. The order matters. Implementing every feature at once makes it harder to determine whether a bug comes from instruction parsing, state management, control flow, or an interaction between components.
A sensible development roadmap
- Define the instruction set and document each opcode.
- Implement the operand stack and basic execution state.
- Build the fetch–decode–execute loop.
- Add arithmetic operations and termination.
- Add jumps and conditional branches.
- Introduce validation and structured runtime errors.
- Create unit tests for each instruction.
- Add local variables and call frames.
- Build a readable program format or assembler.
- Add execution tracing or a debugger interface.
- Benchmark the interpreter and optimize only where justified.
Benchmark the interpreter and optimize only where justified.
Building a virtual machine brings several systems programming concepts together in one manageable project. It demonstrates how an instruction set acts as a contract, how data structures represent runtime state, and how control flow can be implemented through explicit state changes. It also encourages a different approach to software design. Instead of thinking only in terms of user-facing features, you begin thinking in terms of invariants, valid states, transition rules, and failure conditions. Every instruction becomes a small operation whose effects can be specified and tested. For a computer science student or developer interested in interpreters, language runtimes, compilers, or low-level software, a VM is a useful portfolio project because it can be explained through architecture, code, test cases, and observable execution behavior. Its value comes from a clear design and a verified implementation—not simply from calling it a virtual machine.
A virtual machine makes execution explicit: instructions change state, the interpreter enforces the rules, and tests verify the transitions.
—
Conclusion
A virtual machine in Java is an accessible way to explore the mechanics of program execution. By designing a small instruction set, implementing an operand stack, tracking the program counter, and building an execution loop, you can see how an interpreter transforms instructions into behavior. The most important lessons are about precision and structure. Instruction semantics must be consistent, runtime state must remain valid, control flow must be predictable, and errors must be reported clearly. Testing each instruction and then testing complete programs provides the foundation for extending the runtime safely. Start small, verify every operation, and add complexity one feature at a time. Whether your next step is a debugger, a bytecode parser, or support for functions, a carefully designed educational VM gives you a practical foundation for understanding interpreters and runtime systems.
OPEN
Thoughts on the article.