Lesson · Object Initialization & Memory
Memory model basics: values, references, and where they live
20 min readMemory Model Basics
One rule explains aliasing: a variable holds a value, and for an object variable that value is a reference; assignment copies it. Three layers keep the picture honest: what the language guarantees, the runtime map implementations share, and the optimizations the JIT is free to add.
Start with the rule, not the picture
Predict the output, then ask why:
Person p = new Person("Ada"); Person q = p; // does this copy the object? q.name = "Grace"; System.out.println(p.name); // predict before reading on
- It prints `Grace`. No copy of Ada was ever made, because
Person q = p;copies a reference: the value held byp, not the object it identifies. - The one rule: a variable holds a value; for an object variable that value is a reference; assignment copies the value. Aliasing, sharing and collection are all consequences of that sentence.
Everything after this point is a model, not a rule. The lesson builds three layers: what the language guarantees, the runtime picture implementations share, and what the JIT may optimize. Knowing which layer a claim belongs to is what keeps the model honest.
Layer 1: what the language guarantees
Five guarantees, and the consequences the rest of the lesson relies on:
| Guarantee | Consequence |
|---|---|
| A variable holds a value | For object variables that value is a reference: a value that identifies an object. The concrete representation is the implementation's choice. |
| Assignment copies the value | int b = a copies the number; Person q = p copies the reference, so two variables can name one object. Assignment never duplicates an object. |
== on references asks identity | Two references compare equal when they identify the same object, regardless of content. Content comparison is equals, a different question. |
null is a reference to no object | It is a value, not an empty object: reading a field or calling a method through it throws NullPointerException. |
| Objects outlive statements, not scopes | A local disappears when its frame does, but the object keeps existing while any chain of references from a root (a live frame, a static field) can reach it. |
The layer to trust. Heap, stack, pool and metadata are pictures of how implementations work, useful because they predict behaviour; none of them may contradict a guarantee from this table.
Aliasing in six beats
The visual below runs one scenario in six beats. At each beat, ask one question: did a variable's value change, or did the object?
Person p;declares a local reference variable. The frame reserves a slot, but it holds no value yet: the compiler refuses to let you read an uninitialized local.- The right side of the assignment runs first:
new Person("Ada")creates the object and the constructor setsnamefrom its defaultnullto"Ada". The expression evaluates to a reference to that one object. - The assignment stores the reference in
p. One object, one reference: the object is now reachable from the frame. Person q = p;copies the reference value. No constructor runs and no second object appears: two names, one object. That is aliasing.q.name = "Grace";changes the object itself; the statement never mentionsp, yetp.namereadsGracetoo. One mutation, visible through every name.q = null;erases one reference. The object does not move:pstill reaches it, so it stays alive. When no root has a path, an object becomes eligible for collection; that is a lifetime fact, not a scope fact.
Copies happen to values, never to objects. When a change appears through a variable that was not touched, find the aliases: every one of them holds the same reference value.
Assignment & aliasing · one scenario
This visual stays on Layer 1: what the language guarantees. No addresses, no collector; a reference is drawn as an arrow to an identity.
Current statement
Frame · main() · thread
A variable holds a value; an object variable's value is a reference.
Person p; declares a local reference variable. The frame reserves a slot for it, but the slot holds no value yet: the compiler refuses to let you read an uninitialized local.
Layer 2: the runtime picture, drawn carefully
The JVM specification defines runtime areas, not a physical floor plan: per-thread stacks that hold frames, a shared heap for objects and arrays, and per-class storage for static fields. This is the version worth memorising, with the caveats that keep it honest:
| Part of the picture | What it stands for |
|---|---|
| Stack frames | One per active call, per thread: parameters and locals. The frame vanishes when the call returns, and a local cannot outlive it. |
| Heap | Where objects and arrays are managed, shared by every thread. The specification defines a heap; the allocation strategy (and skipping an allocation) belongs to the implementation. |
| Class representation | What static fields belong to: one set per class loader, established at class initialization. Debuggers call this area metaspace. |
| String pool | A pool of interned String instances. Its storage location is implementation-dependent; the identity guarantees are what programs observe. |
- References are not addresses: a reference is a value that identifies an object; the representation (an address or a handle) is the implementation's choice, and programs that never assume otherwise keep working.
- Objects may move: the language exposes identity and reachability, never location, so a collector is free to relocate objects while every reference keeps pointing at them.
- Primitives have no fixed home: the language fixes their size and behaviour, not their physical storage; the JVM decides how each value is held.
Use the picture to predict, never to over-claim. The map below traces one short program through the three regions; every arrow in it is a model of behaviour that Layer 1 guarantees.
Conceptual map · stack, class metadata, heap
Stack · thread · main()
no locals yet
Class metadata · MemoryDemo
static fields not set yet
Heap
no objects
main() has just started: its stack frame is open, nothing has been allocated, and there is nothing on the heap to reach.
Layer 3: what implementations may optimize
The JIT compiler is allowed to make the physical story less literal than the picture, as long as no program can tell the difference:
- Escape analysis: if an object provably never leaves its method, the runtime may keep it out of the heap entirely.
- Allocation elimination and scalar replacement: the object may be split into plain local values, so
newin the source allocates nothing at runtime. Faster, not different: every observable rule still holds. - Identity is the guard rail:
==,hashCode,synchronizedand any reference that escapes pin an object down, forcing the runtime to treat it exactly as the model says.
This layer answers 'why is it fast', never 'what is allowed'. When the layers disagree, the language guarantee wins, the runtime picture explains, and the optimization story only accounts for the speed.
What the model predicts
With the three layers separated, five familiar behaviours stop being trivia:
- Aliasing: two variables can hold the same reference, and through either one, the same object changes.
- Lifetimes: a local ends with its frame; an object ends when no chain of references from a root can reach it.
- Sharing: threads share the heap and race on it; each stack is private, so locals need no synchronisation.
- Copy semantics:
int b = aduplicates data;Person q = pduplicates a reference. One assignment copies a value, the other adds a name. - Optimization: the JIT may erase the physical object when nothing observable can tell; none of the rules above move by a millimetre.
Reachability, not scope, decides when an object dies: when no chain of references from any root can reach it, the collector may reclaim it at its next run. 'Unreachable' describes the object; 'collected' describes the collector, and the two moments differ.
The memory-reading playbook
Reading any program's memory, in order:
- Classify each variable: a primitive value or a reference. Every prediction starts with that split.
- At every assignment, copy the value on the right: a number, or a reference. Never an object.
- Before blaming a mutation, list the aliases: every variable, field and collection element holding the same reference.
- For lifetime questions, trace chains to roots instead of watching scopes; scope ends variables, reachability ends objects.
- Treat location claims ('it is an address', 'it is always on the heap') as Layer 2 or Layer 3 statements, and check them against Layer 1 before repeating them.
Values, references, roots. With those three ideas in place, aliasing, garbage collection and even JIT questions become applications of one sentence: a variable holds a value, and for objects that value is a reference.
The map is a picture; the rules are the language
Three layers answer three questions: what the language guarantees (values, references, assignment), how implementations organise execution (frames, heap, class representation), and what the JIT may optimise (escape analysis, allocation elimination). A reference is not promised to be an address, an object is not promised a fixed location, and a clever runtime may skip an allocation entirely: none of that changes what programs observe, and keeping the layers apart is what keeps the model honest.
Interview angles
What is the difference between a variable and an object?+
A variable is a named slot holding a value; an object is a separate entity with identity and state. For an object variable, the value is a reference: the variable identifies the object, it does not contain it.
Because the variable only holds a reference, assigning null to it does not touch the object, and reassigning it never moves or copies anything but the value. Two variables can hold references to one object, and an object can outlive every variable that once referred to it.
Person p = new Person("Ada"); // the slot p holds a reference; the object exists independently
Common misconception: That the object sits inside the variable. Variables hold values; for objects the value identifies an object that lives and dies on its own schedule.
Follow-up: Which layer of the model answers where the object actually lives?
Does `Person q = p;` create a new object?+
No. It copies the reference value, so both variables identify the same object. Aliasing follows: a change through one name is a change through the other.
No constructor runs and no storage for a second object is used. Every 'who changed my object' investigation starts by listing the references that share it: variables, fields, collection elements, captured values.
Person p = new Person("Ada"); Person q = p; // same object, two references q.name = "Grace"; // p.name now reads Grace as well
Common misconception: That = on objects means 'make a copy'. It means 'copy the value', and for an object variable the value is a reference.
Follow-up: How would you copy the object itself when you truly need one?
Can an object outlive the method that created it?+
Yes. The local variable disappears with its frame, but the object survives as long as any chain of references from a root (a live frame, a static field) can reach it.
Returning a reference, storing it in a field, or adding it to a collection are the ways an object gets published beyond its creating method. Lifetime is a reachability fact, not a scope fact.
static Person make() { Person p = new Person("Ada"); return p; // the local dies; the object is now reachable from the caller }
Common misconception: That objects die when their creating method returns, the way locals do. Locals die with the frame; objects die when unreachable.
Follow-up: What is the smallest thing that keeps an object alive?
Does `q = null;` immediately collect the object?+
No. It removes one path to the object. If no other path from a root remains, the object becomes eligible for collection; actual collection happens whenever the collector next runs.
Eligibility and collection are separate events, and the collector traces reachability rather than watching variables. Weak references deliberately do not count as paths, which is how caches hold entries without keeping the objects alive.
q = null; // one path removed System.out.println(p.name); // the object is still here through p
Common misconception: That nulling is the collection trigger, or that System.gc() forces one. Collection requests are hints; eligibility is the only part of the story your code controls.
Follow-up: Why is System.gc() never a correctness tool?
Do threads share everything on the picture?+
The heap and the class representation, yes; stacks, no. Each thread runs on its own stack, so locals and parameters are private; objects are the shared surface.
Race conditions are heap facts: shared objects mutated without coordination. Copying a shared reference into a local shares the object, not protection; immutability or synchronisation is what protects it.
static Order current; // shared through the class void process() { Order mine = current; ... } // a local copy of the reference, same object
Common misconception: That making a variable local or final makes the object safe. It protects the variable; the object keeps its own story.
Follow-up: What actually protects a shared object?
Are references the same as memory addresses?+
Not as a language guarantee. A reference is a value that identifies an object; its representation is the implementation's business.
The language fixes what references do instead: identity comparisons, null, reachability, and safe movement by the collector. A moving collector may relocate an object while every reference keeps pointing at it, which is exactly where an address-shaped mental model breaks.
Person p = new Person("Ada"); Person q = p; System.out.println(p == q); // true: same object, regardless of representation
Common misconception: That == compares raw addresses. It asks identity: whether two references identify the same object. The bits behind them are unspecified.
Follow-up: What would break if a program assumed references were raw addresses?
Can the JVM allocate an object without a conventional heap allocation?+
Yes, as an optimization. If escape analysis proves an object never leaves its method, the runtime may keep it in registers or on the stack, or eliminate its storage entirely.
Observable behaviour is the constraint: identity comparisons, hashCode, synchronized and any escaping reference force the object to exist for real. This is why the heap belongs to the model, not to the language syntax.
int sum() { Point d = new Point(x, y); // never escapes: may never become a heap object return d.x + d.y; }
Common misconception: That 'new always allocates on the heap' is a language rule. It describes typical execution; implementations may skip storage nothing can observe.
Follow-up: Which operations make an object observably escape?