References Memory And Garbage Collection
Primitive variables hold primitive values. Variables of class, array, and interface types hold references that can point to objects.
Assigning one reference to another does not clone the object. Both variables can point to the same mutable state.
Two states, one object
class Buffer {
String state;
}
public class ReferenceProbe {
public static void main(String[] args) {
Buffer first = new Buffer();
first.state = "ready";
Buffer second = first;
second.state = "used";
System.out.println(first.state);
System.out.println(first == second);
}
}
Output:
used
true
The assignment copies the reference value. Mutating through second changes the one object also reached through first.
first ──┐
├──> Buffer { state: "used" }
second ──┘
Creating new Buffer() a second time would instead create another object with its own fields.
The garbage collector may reclaim an object after no reachable reference can lead to it. You cannot rely on when collection will happen.
Use the question below to trace two variables after a reference assignment.