Java Bytecode
What is Bytecode?
Bytecode is an intermediate representation between source code and machine code. It allows Java to be platform-independent, as Java Virtual Machines (JVMs) on different systems interpret the same bytecode consistently. Java programs compile into bytecode (.class files), which the JVM executes. This makes Java programs portable across platforms with a JVM.
How Java Bytecode Works
Compilation Process
Java source code is compiled by the javac compiler into bytecode, which resides in .class files.
Class Files Structure
It contains headers, constant pools (with metadata and literals), method definitions, field information, and more.
Most notably, it contains the bytecode of each method.
Java Bytecode Instructions and the JVM Stack
Stack-Based Architecture
Java bytecode operates on a stack, pushing and popping values rather than using direct memory addresses or registers. This is in contrast with register-based architecture.
Get Tzehenn’s stories in your inbox
Join Medium for free to get updates from this writer.
Why? Portability (abstract away the underlying hardware)
Basic Instructions
iload,istore,return,if_icmpeq,goto,invokestatic,invokevirtual
Example
int a = 5;
int b = 10;
int sum = a + b0: iconst_5
1: istore_1
2: bipush 10
4: istore_2
5: iload_1
6: iload_2
7: iadd
8: istore_3Here’s what’s happening in each step:
iconst_5- Pushes the integer value 5 onto the stack.istore_1- Stores the top integer (5) from the stack into the first local variable (a).bipush 10- Pushes the byte value 10 onto the stack.istore_2- Stores the top integer (10) from the stack into the second local variable (b).iload_1andiload_2- Loads the integers a and b onto the stack.iadd- Pops the two top integers off the stack, adds them, and pushes the result (sum) back onto the stack.istore_3- Stores the result from the stack into the third local variable (sum).
Performance and Optimization
Just-In-Time (JIT) Compilation
- The JVM does this by converting frequently executed bytecode into native machine code during runtime, rather than interpreting the bytecode every time it is executed.
- This process helps reduce the overhead associated with interpreting bytecode and speeds up program execution, especially for performance-critical code.
Bytecode (Static) Verification
- Bytecode verification becomes crucial to ensure that the generated intermediate code adheres to the rules and constraints of the target platform. This step is essential to prevent potential runtime errors and security vulnerabilities that could arise due to faulty bytecode.
- Done during class-loading phase, when you start executing the program (but before any execution really starts)
- Some errors can be detected
- Invalid Method calls (MethodNotFound, most likely from mismatched binary versions)
- Type Mismatches (ClassCastException)
- Accessing invalid memory location
- Corrupted bytecode in general, maybe from bytecode manipulation
- This sort of verification cannot be done in other languages like C++/Rust because their code is compiled directly into binary
Inspecting and Modifying Bytecode (Bytecode Manipulation)
- An advanced Java technique with a profound impact on areas like performance tuning, program analysis, and language extension.
- It enables developers to modify the bytecode of compiled Java programs, allowing them to adjust the program’s behavior, add new functionalities, or optimize performance — all without changing the original source code.
- This process involves directly altering, adding, or removing bytecode instructions, allowing for deeper modifications than what’s achievable through standard Java source-level coding.
Decompiling Bytecode
Show how tools like javap can display bytecode, and tools like IntelliJ IDEA can decompile .class files.
Real-World Applications
Tools and Frameworks for Bytecode Manipulation
Several tools and frameworks are used for bytecode manipulation:
- ASM: A low-level bytecode manipulation library that allows fine-grained control over bytecode generation and modification. Used by CGLIB library
- Byte Buddy: A higher-level library that makes it easier to create, modify, and manage bytecode with an easier API.
Dynamic Proxy Generation
A proxy is a wrapper object that acts as an intermediary between the caller and the actual object, potentially adding some functionality
2 types:
- JDK Dynamic Proxies
- CGLIB Proxies: Uses bytecode manipulation under the hood via ASM, a low-level bytecode manipulation library
Lazy initialisation in Spring
- For beans configured with
@Lazy, Spring defers their instantiation until the bean is first accessed - Proxies are used to wrap the actual bean, and the proxy handles the first access to initialise the bean
Java Agents and Instrumentation
- Java agents are classes that implement the
java.lang.instrument.Instrumentationinterface and can be specified at JVM startup. - Allow code to be injected into the app before/after classes are loaded by the JVM: Can be loaded via the
-javaagentJVM option, and it operates in the premain or agentmain methods - Examples of how it helps profiling: Method entry and exit logging, Code injection
- Mockito: One of the most powerful uses of Java agents is injecting behavior into existing applications at runtime, such as modifying how classes behave, introducing new classes or methods, or altering the control flow.




