Skip to content

Where Java puts your objects

BasicsUnder the hood

Change a field inside a method and the caller sees it; change a parameter and the caller does not. That follows from where Java keeps each value: locals on the stack, objects on the heap, references between them.

01 The question

Here is a small program. move changes two things it was given, but only one of the changes survives. Before reading on, guess what it prints.

Move.java
public class Move {
static class Point {
int x, y;
Point(int x, int y) { this.x = x; this.y = y; }
}
static void move(Point q, int d) {
q.x += d;
d = 0;
}
public static void main(String[] args) {
int n = 2;
Point p = new Point(1, 2);
move(p, n);
System.out.println(p.x + " " + n);

It prints 3 2. p.x changed, n did not. To see why, you need two places in memory.

02 Two places: the stack and the heap

Each thread has its own stack. Every method call pushes a frame onto it, with a slot for each local variable and parameter. When the method returns, the frame is popped and its slots are gone. Pushing and popping is just moving a pointer, so it is very cheap.

Every object, made with new, lives on the heap, one shared area for all threads. An object stays there as long as something still refers to it; the garbage collector reclaims it later.

A local variable of a primitive type (int, double, boolean...) holds its value in the frame. A local of any other type holds a reference: in effect, the address of an object on the heap.

03 Run the program one line at a time

Watch the stack on the left and the heap on the right. Frames show their slots as name=value; p→#1 means p holds a reference to object #1.

One call, two frames, one object
Step 1 of 10
main thread · call stack
Empty
heap · shared by all threads
Empty
  • pushed or made
  • written now
  • read or followed
  • printed

Before main runs, this thread's stack is empty and nothing is on the heap yet. (The JVM has made objects of its own, such as args; they are left out.)

nothing yet running

Both rules from the start now follow. q was a copy of the reference, so it led to the same object, and the change to x stuck. d was a copy of the number, so changing it touched only move's frame. Java always passes arguments by value; for objects, the value it copies is the reference.

04 Where each kind of value lives

In HotSpot, the usual JVM (JDK 8 and later)
You writeWhere it lives
int n = 2; (a local)In the method's frame on the stack
Point p = new Point(1, 2);The reference in the frame; the Point on the heap
int x; (a field)On the heap, inside its object: fields go where the object goes
new int[10]On the heap: arrays are objects, even of primitives
static int count;On the heap, with the class's `Class` object
"hello" (a literal)A String on the heap, shared through the string pool

This is the model the language promises, and it is what your code means. HotSpot's JIT compiler may go further: when escape analysis proves an object never leaves a method, it can skip the heap and keep the fields in registers. Your program behaves the same; it just runs faster.

05 Fill each one yourself

Each thread's stack has a fixed size, set with -Xss. Recurse without stopping and you run out of frames:

Deep.java
public class Deep {
static int depth = 0;
static void down() {
depth++;
down(); // never returns: one more frame each time
}
public static void main(String[] args) {
try {
down();
} catch (StackOverflowError e) {
System.out.println("StackOverflowError at depth " + depth);
}
}
}
Shell
$ javac Deep.java
$ java Deep
StackOverflowError at depth 46160
$ java -Xss256k Deep
StackOverflowError at depth 1479

The exact depths depend on the JVM, the platform and how big each frame is (these are from JDK 17 on macOS). The default stack size is typically 1 MB on 64-bit Linux; this Mac used 2 MB, which java -XX:+PrintFlagsFinal -version shows as ThreadStackSize.

Stack runs outStackOverflowErrorOne thread nested too many calls. Usually runaway recursion. Sized per thread with -Xss.
Heap runs outOutOfMemoryErrorLive objects no longer fit, even after garbage collection. Sized for the whole JVM with -Xmx.

06 When it bites

static void swap(Point a, Point b)Swapping through parametersAssigning a = b inside the method changes only the copies in its frame. The caller's variables still point where they did.
new String("a") == new String("a")Comparing objects with ==== compares the references, so two equal objects at different heap addresses are not ==. Use equals.
Integer a = 128, b = 128; a == bBoxed numbersInteger values are objects. Java caches the ones from -128 to 127, so == is true for 127 and false for 128 by default. Compare with equals or unbox to int.
list.add(x) from two threadsSharing heap objects between threadsLocals are private to a thread, because each thread has its own stack. The objects they point to are shared. Two threads holding references to one ArrayList need locking or a concurrent collection.

07 Check yourself

Question

int[] a = {1, 2}; int[] b = a; b[0] = 9; What is a[0]?

Question

A Point object has a field int x. Where is x stored?

Question

A method sets its parameter p = new Point(0, 0). Does the caller's variable change?

08 Practise this

Was this tutorial useful?Your vote tells us what to improve next.
Spotted a mistake, or something unclear?