Lesson · JVM Internals
The class file: the binary contract
15 min readThe Class File
magic number to attributes, walked in order: the constant pool everything points into, the Code attribute that holds your bytecode, and the reason a changed constant in a library can silently keep running the old value until callers are recompiled.
The artifact nobody reads until it breaks
Two builds of the same library met in production, and the application died on UnsupportedClassVersionError before it ran a line of its own code. A month later the same team shipped a dependency bump, and a method that existed in the source threw NoSuchMethodError at runtime. Both failures were fully readable in the binaries, and nobody had opened one.
A .class file is not an opaque blob. It is a documented structure, about ten sections long, and every field of it answers a question you eventually ask: which Java release produced it, which method does this call target, where does this constant come from. This lesson walks that structure in the order it appears.
A class file is a constant pool plus descriptions of what uses it. Hold that sentence and the layout stops being trivia.
Ten sections, always the same order
The format is a flat sequence of sections with lengths and counts declared ahead of their contents, so a reader never has to guess where anything ends. javac writes them in one fixed order, and every tool that reads class files assumes it.
Step through the sections below. Each step shows the bytes or the entries that section contributes, and what later sections do with it.
Counts come first, contents follow. Every section announces how many items it holds, which is why a class file can be parsed in one forward pass with no backwards seeking.
Class file · Greeting.class
The walk covers magic, versions, count, pool, flags, this and super, interfaces, fields, methods and attributes, in that order.
Ten sections, one fixed order: magic, minor and major version, pool count, constant pool, access flags, this and super, interfaces, fields, methods, attributes. The player walks them in that order, one stop per section.
Magic and version: what every reader checks first
The first four bytes are the format signature 0xCAFEBABE, and the four bytes after them are two version numbers. A tool that reads those eight bytes already knows it is looking at a class file, and which Java releases can load it.
The major version moves by one per release, so it doubles as a release label. A JVM refuses to load a class file whose major version it does not recognize: that refusal is UnsupportedClassVersionError, and it is thrown at load time, which is exactly where you want version mismatches to surface.
javac --release 17 Lib.java # API pinned to 17, class file version 61 javac -source 17 -target 17 Lib.java # class file version only: newer JDK APIs still compile # --release is the cross-compilation that actually works: it reads JDK 17 signatures # from ct.sym, so calling an API added in 21 fails at compile time, not at runtime.
| Major version | Java release | Notes |
|---|---|---|
| 45 | Java 1.1 | the floor of the numbering; the format predates Java 5 |
| 52 | Java 8 | the version most of the pre-modular ecosystem targets |
| 61 | Java 17 | an LTS release; a common --release 17 target |
| 65 | Java 21 | an LTS release; virtual threads and records patterns land here |
| 69 | Java 25 | the arithmetic continues: one more per release, without gaps |
- minor version: 0 for normal builds; preview features set it to 0xFFFF so tooling can spot code that is not fit for production.
- major version: the release gate. A newer JVM accepts older majors (within limits); an older JVM rejects a newer one outright.
- --release vs -target: -source and -target only set the version fields, so code can still reference newer APIs and fail later. --release pins the API surface too.
Eight bytes carry the compatibility story. Reading them first turns most deployment-time version failures into a two-second diagnosis.
The constant pool: everything points here
The pool is the largest section of most class files, and the reason the rest of the format is full of small integers. Names, type descriptors, string literals, numeric literals, and references to fields and methods are all stored here once; every other section stores an index into it.
A reference is not one entry but a small graph. A Methodref points at a Class entry and a NameAndType entry, and each of those points at Utf8 strings. Nothing in the format is stored as text twice if an index will do.
| Kind of entry | Points at | Used by |
|---|---|---|
| Utf8 | nothing; it is the text | every other entry, eventually |
| Class | a Utf8 name such as java/lang/Object | this_class, super_class, references |
| NameAndType | two Utf8 entries: a name and a descriptor | Fieldref, Methodref, InvokeDynamic |
| Fieldref / Methodref / InterfaceMethodref | a Class plus a NameAndType | getstatic, invokevirtual, and friends |
| String / Integer / Long / Float / Double | a Utf8 for String, the raw value otherwise | ldc, ConstantValue |
| MethodHandle / MethodType | the kind and the target of a handle | invokedynamic bootstrap data (since Java 7) |
- The count is one greater than the number of entries, because index 0 is reserved: it is the null reference slots use to mean nothing.
- long and double occupy two entries, and the slot after them stays unusable. An eight-byte constant was made to take two slots in the original design, and the format has kept that quirk ever since.
- The pool is per class, not per loader: a class file carries its own; the runtime constant pool the JVM builds from it is one of the structures the method area holds.
- New entry kinds arrive without breaking old readers by version gating: MethodHandle, MethodType and InvokeDynamic came with Java 7, and CONSTANT_Dynamic arrived in Java 11, each usable only when the class file version allows it.
Every section after the pool is a list of indices. When a lookup surprises you, the answer is the pool entry it points at, one hop away.
Class file · one pool, ten sections
later sections store small integers; the pool stores the textin order, top to bottom
counts first, contents afterthe constant pool
count = entries + 1Index 0 is reserved as the null reference, which is why the count is one greater than the number of entries.
two lookups, start to finish
one hop through a Class entry: the format never stores the name twice.
#7 Fieldref names a class and a name-and-type; each of those is an index again.
Fields and methods: flags, descriptors, and Code
Both member sections follow one shape: a count, then that many descriptions of the same form. A field or method is a set of access flags, a name index, a descriptor index, and its own list of attributes. If that sounds thin, it is: everything interesting about a method is in its attributes.
Descriptors encode types as compact strings. A method descriptor lists parameters in parentheses and the return type after, so (I)Ljava/lang/String; is a method taking an int and returning a String. Reading them is a five-minute skill that pays back every time you read a stack trace from a reflection-heavy library.
- Field descriptors: I for int, J for long, D for double, Z for boolean, Ljava/lang/String; for a class, [I for int[].
- Method descriptors: the form is (parameters)returnType, with void written as V.
- The Code attribute: one per concrete method and constructor. It holds max_stack, max_locals, the bytecode array, an exception table, and nested attributes such as LineNumberTable.
- max_stack and max_locals are computed by javac at compile time, and the runtime trusts them: the verifier checks that the code never pushes more than max_stack or touches a local outside max_locals.
- ConstantValue: for a static final field the compiler could evaluate, the value is stored on the field description, and no code runs to assign it. That is why such a field needs no static initializer.
The interesting part of a method is its attributes. name and descriptor identify it; the Code attribute is what actually executes.
Attributes: Code now, room for the future later
An attribute is a named blob with a declared length, which means a reader can skip one it does not understand. That single design decision is why the class file format has survived decades of new features: an old tool ignores what it does not know instead of failing.
The JVM itself only requires a few attributes to be understood: Code, ConstantValue, StackMapTable for verification, and BootstrapMethods for linked call sites. The rest are breadcrumbs for debuggers, profilers, IDEs and reflection.
| Attribute | Attached to | What it carries |
|---|---|---|
| Code | methods | max_stack, max_locals, bytecode, exception table, nested attributes |
| StackMapTable | Code | verification frames at branch targets, so the verifier checks types instead of deriving them |
| ConstantValue | fields | a compile-time constant, stored on the field itself |
| SourceFile, LineNumberTable, LocalVariableTable | class / Code | debug info for stack traces and debuggers; absent in some builds |
| Signature | class, field, method | generic types, erased in the descriptors but preserved here for reflection |
| BootstrapMethods | class | the bootstrap methods that invokedynamic call sites link against, since Java 7 |
Unknown attributes are ignored, not rejected. That is how the format gains features without breaking older tools or JVMs.
javap -v: the everyday reader
You do not need a hex editor. javap ships with the JDK and prints the structure directly; -v includes the constant pool and the attribute details that -c leaves out. Reading a dump is a fixed order of questions, not a hunt.
$ javap -v Greeting.class Classfile Greeting.class minor version: 0 major version: 61 // 61 = Java 17 flags: (0x0021) ACC_PUBLIC, ACC_SUPER this_class: #13 // Greeting super_class: #2 // java/lang/Object interfaces: 0, fields: 1, methods: 2, attributes: 1 Constant pool: #1 = Methodref #2.#3 // java/lang/Object."<init>":()V #2 = Class #4 // java/lang/Object #3 = NameAndType #5:#6 // "<init>":()V ... #7 = Fieldref #8.#9 // java/lang/System.out:Ljava/io/PrintStream; ... #13 = Class #14 // Greeting #14 = Utf8 Greeting { static final int VERSION; descriptor: I flags: (0x0019) ACC_PUBLIC, ACC_STATIC, ACC_FINAL ConstantValue: int 2 // no code assigns this field public static void main(java.lang.String[]); descriptor: ([Ljava/lang/String;)V flags: (0x0009) ACC_PUBLIC, ACC_STATIC Code: stack=2, locals=1, args_size=1 0: getstatic #7 // Field java/lang/System.out:Ljava/io/PrintStream; 3: iconst_2 // VERSION, copied: there is no field access here 4: invokevirtual #22 // Method java/io/PrintStream.println:(I)V 7: return } SourceFile: "Greeting.java"
- Read the version line first: minor and major decide which JVMs can load the file at all.
- Read this_class and super_class, and check the interface list: that is the type hierarchy the file claims.
- Scan the constant pool for the symbols you care about. javap adds the resolved text as a comment, so a Methodref reads as Class.name:(descriptor)return.
- Find the method by name and descriptor, then read its Code block: stack and locals announce the frame the method needs, and the instruction list is what runs.
- Look for ConstantValue on fields when a value seems to arrive from nowhere, and for BootstrapMethods when the class uses invokedynamic.
javap -v answers structure questions; javap -c answers behaviour questions. Reach for the pair before you reach for a decompiler.
Constants are baked into their callers
Here is the failure this lesson exists to prevent. A library exposes public static final int TIMEOUT = 30. Every class that reads it gets the number 30 copied directly into its own bytecode, because 30 is a compile-time constant and javac inlines constant expressions. Ship version 2 of the library with TIMEOUT changed to 60 and recompile only the library, and the callers keep running with 30. Nothing throws, nothing logs, the dependency is definitely updated.
The rule is precise rather than mystical. A field is inlined when it is static final, its type is primitive or String, and its initializer is a constant expression. An Integer, an array, or anything produced by a method call is not, so callers read the field at runtime and see the new value immediately.
- Inlined:
static final int,static final String, and any other compile-time constant expression, including constants built from other constants. - Not inlined: boxed types such as
static final Integer, arrays, and anything computed at class initialization. Those are fields, read through the pool. - The fix: recompile every module that reads the constant. That is exactly what build tools do when they detect a changed library, and what a manual hot-patch classpath edit skips.
- The safer alternatives: a non-constant accessor (a method returning the value), an enum constant, or a value from configuration. Anything that cannot be constant-folded survives a library bump.
Constants are baked into callers: change one and recompile them. If a value must be able to move without a rebuild, it cannot be a compile-time constant.
The constant that did not change
You bumped the library, redeployed it, and the old value is still in play. javac copied the constant into every caller at build time, and those callers were never rebuilt, so their bytecode still says 30. There is no runtime fix: the fix is a recompile of the readers, or a redesign that stops the value from being a compile-time constant in the first place.
Interview angles
What do the first eight bytes of a class file tell you?+
Four magic bytes, 0xCAFEBABE, then the minor and major versions. The version pair decides which JVMs can load the file: an older JVM rejects a newer major version with UnsupportedClassVersionError.
The major version moves one step per Java release, so 52 is Java 8, 61 is Java 17 and 65 is Java 21. Preview features set the minor version to 0xFFFF, so tooling can identify non-production builds.
Common misconception: That you need a hex editor to see this. javap -v prints both numbers, and the line is the first thing to check when a deployment fails before main runs.
Why does a class file have a constant pool?+
To store every name, descriptor and literal once, and let the rest of the file reference them by index. It keeps the format compact and makes references uniform, since a method call, a field access and a literal all resolve through the same table.
A method reference is a small graph: a Methodref points at a Class entry and a NameAndType entry, and each of those points at Utf8 text. The pool count is one greater than the number of entries, because index 0 is reserved as the null reference.
Common misconception: That the pool is a dictionary of strings. It is a table of typed entries, including handles and call site descriptors added in later releases.
Follow-up: What happens to a long value in that pool?
What is in the Code attribute?+
max_stack, max_locals, the bytecode array, an exception table, and nested attributes such as LineNumberTable. Every concrete method and constructor has exactly one.
javac computes max_stack and max_locals while it emits instructions, and the verifier then checks the code never exceeds them: the operand stack can never grow past max_stack, and no instruction may touch a local outside the declared range.
Common misconception: That Code is the whole method. The method description also carries flags, a name, a descriptor and any other attributes; Code is one of them, just the executable one.
How does the class file format stay compatible with new features?+
Attributes are named blobs with declared lengths, and readers skip ones they do not know. New kinds of constant pool entries are guarded by the class file version, so old JVMs never meet them in a file they accepted.
That is how StackMapTable, Signature, BootstrapMethods and Module arrived without breaking any existing tool. The price is that an old reader cannot always act on the new information, so it operates without it rather than failing.
Follow-up: What must a JVM still understand even today?
A library changed a public static final int, and consumers still see the old value. Why?+
The value was a compile-time constant, so javac inlined it into every caller at build time. Only a recompile of those callers picks up the new value; the library jar alone cannot change bytecode that no longer references it.
Inlining applies to static final fields whose type is primitive or String and whose initializer is a constant expression. A static final Integer, an array, or a value computed by a method is read through the field at runtime and updates without a recompile.
public class Lib { public static final int TIMEOUT = 30; // copied into every caller public static final Integer LIMIT = 30; // a field read: not copied public static int timeout() { return 30; } // a call: not copied }
Common misconception: That only String constants are inlined. Any compile-time constant expression is, including primitive arithmetic, string concatenation of constants, and constants built from other constants.
What does javac --release change compared to -source and -target?+
--release pins two things at once: the class file version and the API surface, because javac reads the target release signatures instead of the running JDK. -source and -target set the version fields but leave the newer APIs visible, so code can compile and then fail at runtime.
That is the difference between cross-compiling safely and compiling with a version sticker on it. Use --release whenever the artifact has to run on an older JVM.
Follow-up: Which class file version does --release 17 produce?