Sub topic 4
References, Shared Objects, Null, and Identity
A class describes a kind of object. An object is one item created from a class. In Java, you usually work with an object through a reference.
A reference is a value that tells Java which object to use. A variable can hold a reference, and more than one variable can hold a reference to the same object.
This matters because a change made through one reference is visible through the others. It also means you can change which object a variable refers to without changing the object itself.
This chapter uses the classes, fields, methods, and new expression you have already seen.
A reference is not the object
Consider a class named Counter. Each Counter object has a field, a piece of data that belongs to it, named value. Its increment method, a named action, increases that value.
When you write Counter first = new Counter();, Java creates a Counter object and stores a reference to it in first.
When you write Counter shared = first;, Java copies the reference. It does not create another Counter. Both variables now refer to the same object.
A reference differs from a primitive value. A primitive value is a simple value such as an int. If you write int a = 1; int b = a;, both variables hold the number 1. Changing b later does not change a.
With object references, copying a reference still gives each variable its own value. But those values can point to the same object.
Try shared references
Save this program as ReferenceDemo.java.
class Counter {
int value;
void increment() {
value++;
}
}
public class ReferenceDemo {
static void increase(Counter item) {
item.increment();
}
static void replaceLocally(Counter item) {
item = new Counter();
item.increment();
}
public static void main(String[] args) {
Counter first = new Counter();
first.increment();
Counter shared = first;
shared.increment();
Counter other = new Counter();
other.increment();
other.increment();
System.out.println("After shared change: " + first.value);
System.out.println("Shared reference? " + (first == shared));
System.out.println("Same object as other? " + (first == other));
increase(first);
System.out.println("After method change: " + first.value);
replaceLocally(first);
System.out.println("After method replacement: " + first.value);
first = null;
System.out.println("First is null? " + (first == null));
System.out.println("Shared still sees: " + shared.value);
if (first != null) {
first.increment();
} else {
System.out.println("Missing counter");
}
}
}Compile and run it from the folder containing the file:
javac ReferenceDemo.java
java ReferenceDemoThe output is:
After shared change: 2
Shared reference? true
Same object as other? false
After method change: 3
After method replacement: 3
First is null? true
Shared still sees: 3
Missing counterThe program uses static so that main can call the helper methods without creating a ReferenceDemo object. The important part for now is what happens to the references passed to those methods.
Follow the shared object
A new Counter starts with value set to 0. That is the default value for an int field. The first call to first.increment() changes it to 1.
Next, shared receives a copy of the reference in first. The call shared.increment() changes the same counter to 2. So reading first.value also gives 2.
The program then creates other and increments it twice. At that point, the references look like this:
The two counters have the same field value, but they are separate objects. If you increment other, the counter shared by first and shared does not change.
A variable that shares an object with another variable is sometimes called an alias. Aliases are useful when several parts of a program need to work with the same object. They can also cause surprises if one part changes an object that another part is using.
Identity with `==`
An object's identity is what makes it that particular object, separate from every other object. Two objects can have the same field values and still have different identities.
For reference variables, == checks whether they refer to the same object. It also gives true if both references are null.
In the example:
first == sharedistruebecause both refer to one counter.first == otherisfalsebecauseotherrefers to a different counter.- Both counters have
valueequal to2when these checks run. That does not make them the same object.
The == check does not compare the contents of two objects. Comparing objects by their contents is a separate topic from identity.
Changing an object versus changing a reference
These two actions are easy to mix up:
shared.increment()changes the counter thatsharedrefers to. Anyone holding a reference to that counter can see the changed value.first = nullchanges the value stored in thefirstvariable. It does not change the counter or the value stored inshared.
After first = null, the program can still read the counter through shared. At that point, the counter's value is 3, so shared.value prints 3.
You can also assign a reference variable a reference to a different object. That changes which object the variable refers to; it does not move or copy the old object's data.
Passing a reference to a method
A parameter is a variable declared by a method to receive a value. An argument is the value you supply when you call that method.
Java passes arguments by value. That means the method receives a copy of the value. For an object argument, the copied value is a reference, not a copy of the object.
Look at the call increase(first). The parameter item receives a copy of the reference in first. Both refer to the same counter. So item.increment() changes that counter, and first.value becomes 3.
Now look at replaceLocally(first). Its parameter also starts with a copy of the reference in first. But the statement item = new Counter(); changes only the parameter. It makes item refer to a new counter; it does not change first. The method increments the new counter, while the original counter stays at 3.
This is the same distinction as before: changing an object can be visible through shared references, but assigning a variable changes only that variable.
What `null` means
null is a special reference value that means “no object.” For example, first = null; makes first refer to no counter.
The name null is not the text "null", and it is not an empty Counter. You cannot call an object method through a reference whose value is null.
An exception is a signal that something went wrong while a program was running. If the program called first.increment() after setting first to null, Java would throw a NullPointerException. Unless the program handles that exception, it stops.
You can check for null before using a reference. The example uses first != null, which asks whether first has a value other than null. Because first is null, the program prints Missing counter instead of calling the method.
A local variable is a variable declared inside a method. Java requires you to assign a local variable before reading it. Writing Counter current; alone does not make it safe to use current.
A reference field, by contrast, gets null as its default value if no other value is assigned to it.
When an object is no longer reachable
Setting one reference to null does not remove an object that can still be reached through another reference. In the example, shared still reaches the counter after first is set to null.
Java uses garbage collection to reclaim memory used by objects that a running program can no longer reach. Garbage collection is automatic, but Java does not promise exactly when an unreachable object will be reclaimed. You do not need to set every local reference to null to make this happen.
Practice
Exercise
A program creates a counter in a, assigns Counter b = a;, then calls b.increment(). If the counter started at 0, what does a.value show?
Show answer
It shows 1. a and b refer to the same counter, so the change through b is visible through a.
Exercise
After Counter b = a;, the program sets a = null;. Does b become null too?
Show answer
No. Only the value in a changes. b still refers to the original counter.
Exercise
Two separate counters both have value 5. What does a == b return, and why?
Show answer
It returns false. Equal field values do not make two separate objects the same object.