Code attribute

The method's bytecode and everything the JVM needs to run it: how big to make the frame (max_stack and max_locals), the instructions, and the exception table that says which handler catches what over which range..

Appears on
method
Since
class file 45.0 (Java 1.0)
javac writes it
for every method with a body
Needed by the JVM
yes: the JVM reads it to load, verify or run the class

Layout

TypeFieldWhat it holds
u2attribute_name_indexa Utf8: "Code"
u4attribute_lengthbytes after this field
u2max_stackdeepest the operand stack gets, in slots
u2max_localslocal variable slots, including this and the parameters
u4code_lengthbytes of bytecode (under 65536)
u1[code_length]codethe instructions
u2exception_table_length
{u2,u2,u2,u2}[…]exception_tablestart_pc, end_pc, handler_pc, catch_type
u2attributes_count
attribute_info[…]attributesLineNumberTable, LocalVariableTable, StackMapTable, …

What it is for

The method's bytecode and everything the JVM needs to run it: how big to make the frame (max_stack and max_locals), the instructions, and the exception table that says which handler catches what over which range.

code_length must be under 65,536, the "code too large" limit that very big static initialisers and generated methods run into.

Abstract and native methods have no Code attribute.

How common it is

JDK 25.0.5's java.base has 61,673 Code attributes, in 6,848 of its 7,391 classes (61,673 on methods).

A real one, byte by byte

From Hello.class (compiled by javac 25), on method <init>:

OffsetBytesFieldValue
87053 bytesCode
87000 1battribute_name_index#27
87200 00 00 2fattribute_length47
87600 01max_stack1
87800 01max_locals1
88000 00 00 05code_length5
8842a b7 00 01 b1code
88900 00exception_table
89100 02 00 1c 00 00 00 06 00 01 00 00 …attributes2

Open in the viewer

Specification: JVMS §4.7, The Code Attribute (Java SE 25).