What is inside a .class file
35 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)A .class file is the binary file javac writes for each class. Its layout is fixed by the Java Virtual Machine Specification: a magic number, a version, a constant pool, and then the class's fields, methods and attributes.
One class file per class
javac writes one .class file for every class, not one per source file. A top-level class Warden becomes Warden.class. A nested class (a class declared inside another class) is named Outer$Inner.class, for example Hostel$Room.class.
Example 1 · Nested, anonymous and local classes get their own names
import java.util.function.Supplier;
class Warden { String name = "Mr Rao";}
public class Hostel { static class Room { int number = 101; }
class Notice { String today = "Rajma chawal"; }
public static void main(String[] args) { Runnable bell = new Runnable() { // anonymous class public void run() { System.out.println("Lights out!"); } };
class Visitor { // local class String name = "Parent"; }
Supplier<String> gate = () -> "Gate closes at 10 pm"; // lambda
System.out.println(new Warden().getClass().getName()); System.out.println(new Room().getClass().getName()); System.out.println(new Hostel().new Notice().getClass().getName()); System.out.println(bell.getClass().getName()); System.out.println(new Visitor().getClass().getName()); System.out.println(gate.get()); }}Warden Hostel$Room Hostel$Notice Hostel$1 Hostel$1Visitor Gate closes at 10 pm
What this code does
getClass().getName()prints the binary name of each class, the same name as its.classfile:Hostel$Room,Hostel$Notice,Hostel$1for the anonymousRunnableandHostel$1Visitorfor the local class.Roomis a static nested class andNoticeis an inner class.javac --release 17 Hostel.javawrites six files:Hostel.class,Hostel$Room.class,Hostel$Notice.class,Hostel$1.class,Hostel$1Visitor.classandWarden.class(a second top-level class in the same file). The lambdagategets no file; its code lives in a private method ofHostel.
Classes without a name get numbers. The first anonymous class in Hostel becomes Hostel$1.class, and a local class Visitor (declared inside a method) becomes Hostel$1Visitor.class. Lambdas are different. On Java 8 and later, javac writes no class file for a lambda. It puts the lambda's code in a private method, and the JVM builds a small class for it while the program runs.
.class file, including the $ ones. A missing Hostel$Room.class causes NoClassDefFoundError the first time Room is used.Magic number and class file version
Every class file starts with the same 4 bytes: CA FE BA BE, the magic number. The JVM checks them first. A file that starts with anything else is rejected with ClassFormatError: Incompatible magic value.
Example 2 · Read the magic number and version yourself
import java.io.DataInputStream;import java.io.IOException;import java.io.InputStream;
public class ClassVersionDemo { static String javaRelease(int major) { return major >= 49 ? "Java " + (major - 44) : "older than Java 5"; }
public static void main(String[] args) throws IOException { try (InputStream in = ClassVersionDemo.class.getResourceAsStream("ClassVersionDemo.class"); DataInputStream data = new DataInputStream(in)) { int magic = data.readInt(); // 4 bytes int minor = data.readUnsignedShort(); // 2 bytes int major = data.readUnsignedShort(); // 2 bytes
System.out.printf("Magic number: %X%n", magic); System.out.println("Minor version: " + minor); System.out.println("Major version: " + major + " (" + javaRelease(major) + ")"); } }}Magic number: CAFEBABE Minor version: 0 Major version: 61 (Java 17)
What this code does
getResourceAsStream("ClassVersionDemo.class")opens the program's own class file.DataInputStreamreads big-endian numbers, which is the byte order class files use:readIntreads 4 bytes,readUnsignedShortreads 2.- This program was compiled with
javac --release 17, so it reports 61. Compile it with plainjavacon JDK 21 and it reports 65 (Java 21).
The next 4 bytes are the class file version: a minor version (2 bytes, 0 for normal classes) and a major version (2 bytes). From Java 5 onwards, major version = Java release + 44. So 52 is Java 8, 55 is Java 11, 61 is Java 17 and 65 is Java 21. The major version tells you the oldest JVM that can load the class. A class with major version 61 runs on Java 17 and every newer JVM.
The constant pool, fields, methods and attributes
The constant pool is a numbered table inside a class file that holds names, types, large constants and symbolic references. Instructions point into it by number, such as getfield #8.
After the version comes the constant pool: a numbered table of the constants the class uses.
public class Fees { private int tuition = 45000;
int total(int hostel) { return tuition + hostel; }}Example 3 · javap -v shows the whole layout of Fees.class
javac --release 17 Fees.javajavap -v -p FeesClassfile /.../Fees.class
Last modified 15-Oct-2026; size 289 bytes
SHA-256 checksum 2f968a471aa7e232e61565eb25fb956ad31b9ab890b0a5b844909e0eadcd7cf3
Compiled from "Fees.java"
public class Fees
minor version: 0
major version: 61
flags: (0x0021) ACC_PUBLIC, ACC_SUPER
this_class: #9 // Fees
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
#4 = Utf8 java/lang/Object
#5 = Utf8 <init>
#6 = Utf8 ()V
#7 = Integer 45000
#8 = Fieldref #9.#10 // Fees.tuition:I
#9 = Class #11 // Fees
#10 = NameAndType #12:#13 // tuition:I
#11 = Utf8 Fees
#12 = Utf8 tuition
#13 = Utf8 I
#14 = Utf8 Code
#15 = Utf8 LineNumberTable
#16 = Utf8 total
#17 = Utf8 (I)I
#18 = Utf8 SourceFile
#19 = Utf8 Fees.java
{
private int tuition;
descriptor: I
flags: (0x0002) ACC_PRIVATE
public Fees();
descriptor: ()V
flags: (0x0001) ACC_PUBLIC
Code:
stack=2, locals=1, args_size=1
0: aload_0
1: invokespecial #1 // Method java/lang/Object."<init>":()V
4: aload_0
5: ldc #7 // int 45000
7: putfield #8 // Field tuition:I
10: return
LineNumberTable:
line 1: 0
line 2: 4
int total(int);
descriptor: (I)I
flags: (0x0000)
Code:
stack=2, locals=2, args_size=2
0: aload_0
1: getfield #8 // Field tuition:I
4: iload_1
5: iadd
6: ireturn
LineNumberTable:
line 5: 0
}
SourceFile: "Fees.java"What this code does
- Top to bottom you can see the parts in file order: version, flags, this and super class, the counts (1 field, 2 methods, 1 attribute), the constant pool with 19 entries, the field
tuition, the methods and theSourceFileattribute. - javac added a constructor
Fees()you never wrote: the default constructor. It callsObject.<init>and then stores 45000 intotuition, because field initialisers are copied into every constructor.45000is too big for an instruction, so it lives in the pool as#7 = Integer 45000.
Example 4 · A tiny class file reader
import java.io.DataInputStream;import java.io.IOException;import java.io.InputStream;
class Student implements Comparable<Student> { private String name; private int marks;
Student(String name, int marks) { this.name = name; this.marks = marks; }
boolean passed() { return marks >= 40; }
public int compareTo(Student other) { return Integer.compare(marks, other.marks); }}
public class ClassFileReaderDemo { static String[] utf8; static int[] classNameAt;
public static void main(String[] args) throws IOException { try (InputStream in = ClassFileReaderDemo.class.getResourceAsStream("Student.class"); DataInputStream d = new DataInputStream(in)) { System.out.printf("magic %X, version %d.%d%n", d.readInt(), d.readUnsignedShort(), d.readUnsignedShort());
readConstantPool(d);
d.readUnsignedShort(); System.out.println("this class: " + className(d.readUnsignedShort())); System.out.println("super class: " + className(d.readUnsignedShort())); int interfaces = d.readUnsignedShort(); for (int i = 0; i < interfaces; i++) { System.out.println("interface: " + className(d.readUnsignedShort())); } printMembers("field", d); printMembers("method", d);
int attributes = d.readUnsignedShort(); for (int i = 0; i < attributes; i++) { System.out.println("attribute: " + utf8[d.readUnsignedShort()]); d.skipBytes(d.readInt()); } } }
static void readConstantPool(DataInputStream d) throws IOException { int count = d.readUnsignedShort(); utf8 = new String[count]; classNameAt = new int[count]; for (int i = 1; i < count; i++) { int tag = d.readUnsignedByte(); switch (tag) { case 1 -> utf8[i] = d.readUTF(); // Utf8 case 7 -> classNameAt[i] = d.readUnsignedShort(); // Class case 8, 16, 19, 20 -> d.skipBytes(2); case 15 -> d.skipBytes(3); case 3, 4, 9, 10, 11, 12, 17, 18 -> d.skipBytes(4); case 5, 6 -> { d.skipBytes(8); i++; } // long, double take two slots default -> throw new IOException("Unknown tag " + tag); } } }
static String className(int index) { return utf8[classNameAt[index]]; }
static void printMembers(String kind, DataInputStream d) throws IOException { int count = d.readUnsignedShort(); for (int i = 0; i < count; i++) { d.readUnsignedShort(); String name = utf8[d.readUnsignedShort()]; String descriptor = utf8[d.readUnsignedShort()]; System.out.printf("%-12s %s %s%n", kind + ":", name, descriptor); int attributes = d.readUnsignedShort(); for (int a = 0; a < attributes; a++) { d.readUnsignedShort(); d.skipBytes(d.readInt()); } } }}magic CAFEBABE, version 0.61 this class: Student super class: java/lang/Object interface: java/lang/Comparable field: name Ljava/lang/String; field: marks I method: <init> (Ljava/lang/String;I)V method: passed ()Z method: compareTo (LStudent;)I method: compareTo (Ljava/lang/Object;)I attribute: Signature attribute: SourceFile
What this code does
- The reader walks the file in order: magic and version, the constant pool (keeping only text and class entries, skipping the rest by size), flags, this and super class, interfaces, fields, methods and attributes.
longanddoubleentries take two pool slots, which is why the loop doesi++for tags 5 and 6. - Two surprises come from javac: a second
compareTo(Object)method, called a bridge method, which lets generic code callcompareToon anyComparable; and aSignatureattribute that remembersComparable<Student>, because descriptors keep only the erased type (Comparable) and the compiler and reflection need the full generic type. utf8holds the text entries, andclassNameAtholds, for each Class entry, the index of its name. Tags 3, 4, 9, 10, 11, 12, 17 and 18 (int, float, references, NameAndType, dynamic) are skipped by 4 bytes, tags 8, 16, 19 and 20 (String, MethodType, Module, Package) by 2, and tag 15 (MethodHandle) by 3.
It holds text (Utf8 entries such as names and types), numbers too big to fit inside an instruction (such as 45000), and symbolic references such as "field tuition of type int in class Fees". Instructions point into it by number: getfield #8.
Then come the access flags (public, final and so on), this class, its superclass and interfaces, a table of fields, a table of methods and a list of class attributes such as SourceFile. Each method's bytecode sits in an attribute called Code. Names are stored in internal form, with slashes instead of dots: java/lang/Object. Types are stored as short descriptors: I is int, and (I)I is a method that takes an int and returns an int. The javap lesson reads them in detail.
UnsupportedClassVersionError
UnsupportedClassVersionError is the error a JVM throws when a class file is newer than the JVM. A JVM loads class files of its own version and older, and the message names both numbers: the class file's version and the highest one this JVM understands.
Example 5 · Too new for the JVM, then fixed with --release
javac FeeReceipt.java # JDK 21, no --release: major version 65java FeeReceipt # run with a Java 19 JVMjavac --release 17 FeeReceipt.javajava FeeReceipt # same Java 19 JVM$ javac FeeReceipt.java $ java FeeReceipt Error: LinkageError occurred while loading main class FeeReceipt java.lang.UnsupportedClassVersionError: FeeReceipt has been compiled by a more recent version of the Java Runtime (class file version 65.0), this version of the Java Runtime only recognizes class file versions up to 63.0 $ javac --release 17 FeeReceipt.java $ java FeeReceipt Receipt for Riya Sharma Tuition: Rs 45000 Hostel: Rs 18000 Total: Rs 63000
What this code does
- JDK 21's javac writes version 65 by default. This JVM is Java 19, which knows versions up to 63, so it refuses the class. A Java 17 JVM would say "up to 61.0".
- After
javac --release 17, the class has version 61 and the same Java 19 JVM runs it. Version numbers in the message map to releases with the +44 rule: 65 is Java 21, 63 is Java 19.
There are two fixes. Compile for the oldest Java your users run, with --release N: javac --release 17 FeeReceipt.java writes major version 61, which Java 17 and every newer JVM accept. Or upgrade the JVM on the server.
--release versus -source and -target
--release N (Java 9 and later) tells javac to compile for Java N: it writes that release's class file version and checks your code against that release's API. The older pair -source N -target N sets only the language level and the version number.
// Java 21import java.util.List;
public class New21 { public static void main(String[] args) { List<String> stops = List.of("Pune", "Lonavala", "Mumbai"); System.out.println(stops.reversed()); // reversed() is new in Java 21 }}[Mumbai, Lonavala, Pune]
That difference matters when you call a method that is newer than your target. With --release 17, javac stops at compile time. With -target 17 alone, javac 21 still sees its own Java 21 library, so the class compiles and then fails on an older JVM with NoSuchMethodError. This program uses List.reversed(), added in Java 21.
Example 6 · Why --release beats -source and -target
javac --release 17 New21.javajavac -source 17 -target 17 New21.javajava New21 # run with a Java 19 JVM$ javac --release 17 New21.java
New21.java:5: error: cannot find symbol
System.out.println(stops.reversed());
^
symbol: method reversed()
location: variable stops of type List<String>
1 error
$ javac -source 17 -target 17 New21.java
warning: [options] system modules path not set in conjunction with -source 17
1 warning
$ java New21
Exception in thread "main" java.lang.NoSuchMethodError: 'java.util.List java.util.List.reversed()'
at New21.main(New21.java:5)What this code does
- With
--release 17, javac checks the Java 17 API and stops at compile time withcannot find symbol. That is the error you want: it appears on your laptop, not on the server. - With
-source 17 -target 17, javac 21 writes version 61 and only warns about the module path. The bug appears later, on an older JVM (Java 19 here), asNoSuchMethodErrorwhen the line runs.
Find the bug
Find the wrong compiler command
Each pair of commands should build for an older Java. Tap the wrong line, then check the fix.
Build for servers that run Java 11.
Round 1 of 3maven.compiler.release in Maven and options.release in Gradle.Next step
Check your understanding
11 quick questions