References vs objects
The variable is never the object. It is a handle, and handles can be copied.
Before you start
In Java there are two kinds of things: **primitives** (int, boolean, double — the eight built-in number-and-truth-value types) and **everything else**. Everything else is an *object*, and every object lives on the heap.
Your variable never *is* the object. It holds a **reference** — a handle — that leads to the object on the heap. If you assign one reference to another, you get two handles pointing at the same object, not two objects.
This lesson makes those handles visible with arrows, so you can see why changing an object through one variable is visible through the other, and what null actually means.
Stack
locals — one slot per variableHeap
every object lives here, alwaysThe value is in the slot. Copying n copies the 10.
Step 1 of 7. A primitive holds its value directly. `int n = 10` puts the number 10 in the variable's slot. There is no object anywhere, and nothing on the heap. The eight primitive types — `int`, `long`, `double`, `boolean` and the rest — work this way. Everything else in Java does not.
Step 01 / 07
A primitive holds its value directly
int n = 10 puts the number 10 in the variable's slot. There is no object anywhere, and nothing on the heap.
The eight primitive types — int, long, double, boolean and the rest — work this way. Everything else in Java does not.
public class Main { static void rename(Point p) { p.x = 99; // changes the caller's object p = new Point(0); // rebinds the local copy only } public static void main(String[] args) { int n = 10; Point a = new Point(1); Point b = a; // copies the reference, not the object b.x = 42; // a.x is now 42 too rename(a); Point c = null; // refers to nothing }}