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
| Type | Field | What it holds |
|---|---|---|
u2 | attribute_name_index | a Utf8: "Code" |
u4 | attribute_length | bytes after this field |
u2 | max_stack | deepest the operand stack gets, in slots |
u2 | max_locals | local variable slots, including this and the parameters |
u4 | code_length | bytes of bytecode (under 65536) |
u1[code_length] | code | the instructions |
u2 | exception_table_length | |
{u2,u2,u2,u2}[…] | exception_table | start_pc, end_pc, handler_pc, catch_type |
u2 | attributes_count | |
attribute_info[…] | attributes | LineNumberTable, 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>:
| Offset | Bytes | Field | Value |
|---|---|---|---|
| 870 | 53 bytes | Code | |
| 870 | 00 1b | attribute_name_index | #27 |
| 872 | 00 00 00 2f | attribute_length | 47 |
| 876 | 00 01 | max_stack | 1 |
| 878 | 00 01 | max_locals | 1 |
| 880 | 00 00 00 05 | code_length | 5 |
| 884 | 2a b7 00 01 b1 | code | |
| 889 | 00 00 | exception_table | |
| 891 | 00 02 00 1c 00 00 00 06 00 01 00 00 … | attributes | 2 |
Specification: JVMS §4.7, The Code Attribute (Java SE 25).