What an object looks like in memory
35 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)Every Java object on the heap is a small block of bytes with three parts: a header the JVM uses for its own bookkeeping, the object's fields, and a few padding bytes so the size is a multiple of 8. This picture explains why even new Object(), with no fields at all, takes about 16 bytes.
The object header: mark word and class pointer
An object header is the bookkeeping at the start of every object: 12 bytes on 64-bit HotSpot with default settings, made of an 8-byte mark word and a 4-byte class pointer.
The object header is the bookkeeping part at the start of every object. On 64-bit HotSpot (the JVM inside OpenJDK and Oracle JDK) with default settings, Java 17 and 21, it is 12 bytes: an 8-byte mark word and a 4-byte class pointer.
Example 1 · The identity hash code lives in the header
class Ticket { final String pnr;
Ticket(String pnr) { this.pnr = pnr; }}
public class IdentityHashDemo { public static void main(String[] args) { Ticket t = new Ticket("4521367890");
int first = System.identityHashCode(t); // computed now, saved in t's header int second = System.identityHashCode(t); // read back from the header System.out.println("First call : " + first); System.out.println("Second call: " + second); System.out.println("Same number both times? " + (first == second));
Ticket copy = new Ticket("4521367890"); // same PNR, different object System.out.println("Other object: " + System.identityHashCode(copy)); System.out.println("Same object? " + (t == copy)); }}First call : 1510467688 Second call: 1510467688 Same number both times? true Other object: 2061475679 Same object? false
What this code does
System.identityHashCode(t)is the numberObject.hashCode()would give. HotSpot computes it on the first call and saves it in the object's mark word, so the second call returns the same number.copyhas the same PNR but is a different object, with its own header and its own identity hash. The numbers differ on every run and every computer.
The mark word holds the object's identity hash code once it is first asked for, its lock state when threads use synchronized on it, and its GC age (how many collections it has survived). This is a simplified picture: the exact bits change with the lock state. The class pointer points to the class's data in Metaspace. That is how getClass() and method calls know what the object is. Methods are not copied into objects: an object holds only its header and its instance fields.
- Picture of
new Object()(simplified): bytes 0 to 7 are the mark word. - Bytes 8 to 11 are the compressed class pointer.
- Bytes 12 to 15 are padding, so the total is 16 bytes, a multiple of 8.
-XX:+UseCompactObjectHeaders (experimental in Java 24, a regular option in Java 25). It is off by default, so this module uses the 12-byte header.Fields and alignment padding to 8 bytes
Padding is unused bytes the JVM adds so every object's size is a multiple of 8. HotSpot starts every object at an address divisible by 8 (the default -XX:ObjectAlignmentInBytes=8), because aligned addresses are faster and simpler for the CPU and the GC.
Example 2 · Estimate sizes: header + fields, rounded up to 8
public class LayoutEstimateDemo { // 64-bit HotSpot, Java 17 and 21, default settings, heap under 32 GB static final int HEADER = 12; // 8-byte mark word + 4-byte class pointer
static int alignTo8(int bytes) { return (bytes + 7) / 8 * 8; // round up to the next multiple of 8 }
static void estimate(String className, String fields, int fieldBytes) { int raw = HEADER + fieldBytes; int total = alignTo8(raw); System.out.printf("%-10s %-28s 12 + %2d = %2d -> %2d bytes (padding %d)%n", className, fields, fieldBytes, raw, total, total - raw); }
public static void main(String[] args) { estimate("Object", "(no fields)", 0); estimate("Attendance", "int present", 4); estimate("Point", "int x, int y", 4 + 4); estimate("Fee", "long amount", 8); estimate("Student", "int, double, String, boolean", 4 + 8 + 4 + 1); }}Object (no fields) 12 + 0 = 12 -> 16 bytes (padding 4) Attendance int present 12 + 4 = 16 -> 16 bytes (padding 0) Point int x, int y 12 + 8 = 20 -> 24 bytes (padding 4) Fee long amount 12 + 8 = 20 -> 24 bytes (padding 4) Student int, double, String, boolean 12 + 17 = 29 -> 32 bytes (padding 3)
What this code does
alignTo8adds 7 and drops the remainder, which rounds up to the next multiple of 8: 20 becomes 24 and 16 stays 16.Attendanceneeds no padding because 12 + 4 is already 16.Studenthas 17 bytes of fields, so 29 is rounded to 32 and 3 bytes are wasted.- For
Fee, the real layout puts thelongat offset 16 (an 8-byte field must start at a multiple of 8), leaving a 4-byte gap after the header. The total is still 24.
To estimate a size, add the 12-byte header and the field sizes, then round up to the next multiple of 8. The field sizes are fixed by the Java type:
byteandboolean: 1 byte.shortandchar: 2 bytes.intandfloat: 4 bytes.longanddouble: 8 bytes.- A reference such as
String name: 4 bytes with compressed references (the default), 8 bytes without. - The JVM may reorder fields to fill gaps, so the order you write them in does not decide the layout.
Order of execution
Estimate the size of one object
Tap the steps in the order you work out the size of a Student object.
Compressed references on 64-bit HotSpot
A compressed reference (HotSpot calls it a compressed oop, for "ordinary object pointer") is a 4-byte reference used on a 64-bit JVM instead of a full 8-byte address. It saves 4 bytes in every reference field and every slot of an object array.
Example 3 · Check compressed references with PrintFlagsFinal
java -XX:+PrintFlagsFinal -version | grep UseCompressedjava -Xmx40g -XX:+PrintFlagsFinal -version | grep UseCompressed bool UseCompressedClassPointers = true {product lp64_product} {default}
bool UseCompressedOops = true {product lp64_product} {ergonomic}
bool UseCompressedClassPointers = true {product lp64_product} {default}
bool UseCompressedOops = false {product lp64_product} {default}What this code does
- Real runs on OpenJDK 21 (the
java -versionlines are left out).-XX:+PrintFlagsFinalprints every JVM setting;grepkeeps the two lines we want. On Windows Command Prompt usefindstr UseCompressedinstead ofgrep. - With the default heap,
UseCompressedOopsistrueand marked{ergonomic}: the JVM chose it. With-Xmx40git isfalse, so references are 8 bytes, whileUseCompressedClassPointersstaystrue.
It works because objects start at multiples of 8. The JVM stores the address divided by 8 in 32 bits, and multiplies by 8 when it follows the reference. 2³² × 8 bytes is 32 GB, so this works only while the heap is below about 32 GB. This is a simplified picture; the JVM also adds a base address. HotSpot turns compressed references on by itself when the maximum heap (-Xmx) is below about 32 GB. From 32 GB up they are off, every reference grows to 8 bytes, and objects with references get bigger. The class pointer stays compressed on Java 15 and later, so the header is still 12 bytes.
-Xmx at 31 GB or less: a 33 GB heap can hold fewer objects than a 31 GB one, because every reference doubles in size.Typical sizes (approximate)
With the rules above you can estimate most small objects. These sizes are for 64-bit HotSpot on Java 17 and 21 with default settings and a heap under 32 GB. Other JVMs or settings give other numbers, so treat them as approximate.
Example 4 · A program that holds objects for you to measure
import java.util.ArrayList;import java.util.List;
class Point { int x; int y;}
class Student { int roll; double cgpa; String name; boolean hosteller;}
public class TypicalObjectsDemo { public static void main(String[] args) throws Exception { List<Object> keep = new ArrayList<>(); for (int i = 0; i < 1000; i++) { keep.add(new Object()); keep.add(new Point()); keep.add(new Student()); keep.add(Integer.valueOf(1000 + i)); // 1000 and above: a new Integer each time keep.add(Long.valueOf(1000L + i)); // same for Long } System.out.println("Holding " + keep.size() + " objects."); System.out.println("In another terminal run: jcmd <pid> GC.class_histogram"); System.out.println("Press Enter to exit."); System.in.read(); System.out.println("Done. Still holding " + keep.size() + " objects."); }}Holding 5000 objects. In another terminal run: jcmd <pid> GC.class_histogram Press Enter to exit. Done. Still holding 5000 objects.
What this code does
- The program keeps 1000 of each kind of object alive in a list, then waits for Enter so you have time to look at it from a second terminal. The last line uses the list again, so the objects stay reachable until then.
Integer.valueOf(1000 + i)andLong.valueOf(1000L + i)create a new wrapper object for each value, so there are at least 1000 of each to count.
Example 5 · Real sizes from jcmd GC.class_histogram
jcmd <pid> GC.class_histogram<pid>: num #instances #bytes class name (module) ------------------------------------------------------- 1: 2634 115848 [B (java.base@21.0.7) ... 7: 1000 32000 Student 8: 1256 30144 java.lang.Long (java.base@21.0.7) ... 10: 1000 24000 Point ... 12: 1262 20192 java.lang.Integer (java.base@21.0.7) 13: 1078 17248 java.lang.Object (java.base@21.0.7) ...
What this code does
- A real run on OpenJDK 21 while Example 4 waited, trimmed with
.... Find the process id withjps -lor plainjcmd. The histogram lists live objects of each class with their total bytes. - Bytes divided by instances gives the size of one object:
Student32000 / 1000 = 32,Point24,Long30144 / 1256 = 24,Integer16 andObject16. These match the estimates. The extra instances belong to the JDK itself.
new Object(): 16 bytes (12 header + 4 padding).Integer: 16 bytes (12 + anintof 4).LongandDouble: 24 bytes (12 + 4 gap + 8).- A
Stringobject: 24 bytes, plus the separatebyte[]that holds its characters. - A class with an
int, adouble, aStringreference and aboolean: 32 bytes.
Next step
Check your understanding
12 quick questions