Sub topic 12
Reference Equality versus Value Equality
Two Java variables can refer to different objects that contain the same value. To compare them correctly, first decide what you want to know:
- Are these references pointing to the same object?
- Do these objects have equal values?
This chapter assumes you can declare variables and run a simple Java program.
Objects and references
An object is a piece of data created by a Java program. A String is an object that holds text.
A reference is a value that identifies an object. A variable of type String holds a reference to a String object. Two variables can hold references to the same object, or to two different objects with the same text.
In the diagram, first and shared refer to the same object. second refers to a different object, even though that object holds the same text.
Comparing references with `==`
When you use == with two references, Java checks whether they refer to the same object. This is called reference equality. It does not check the text inside two String objects.
The != operator asks the opposite question: do the references differ?
Assigning one reference variable to another copies the reference. It does not create a new object. So, after shared = first, both variables refer to the same object.
There is one special case: == also returns true when both references are null. The value null means that a reference does not point to an object.
Comparing values with `equals`
A method is an action that code can call. The equals method lets an object compare itself with another value.
For String objects, equals checks whether the text has the same characters in the same order. The comparison is case-sensitive: "Java" and "java" are not equal.
Try this complete program. Save it as EqualityDemo.java, then compile and run it as you would any Java program.
public class EqualityDemo {
public static void main(String[] args) {
String first = new String("Java");
String second = new String("Java");
String shared = first;
System.out.println("first == second: " + (first == second));
System.out.println("first != second: " + (first != second));
System.out.println("first.equals(second): " + first.equals(second));
System.out.println("first == shared: " + (first == shared));
System.out.println("first.equals(\"java\"): " + first.equals("java"));
}
}The output is:
first == second: false
first != second: true
first.equals(second): true
first == shared: true
first.equals("java"): falseThe two new String(...) expressions create separate objects. Their references are different, so first == second is false. Their text is the same, so first.equals(second) is true.
The variable shared holds a copy of the reference in first. Both refer to the same object, so first == shared is true.
Why `==` can seem to work for strings
A string literal is text written in double quotes, such as "Java". Java can reuse a String object for matching literals. As a result, a reference comparison between two strings may sometimes return true.
That does not make == a text comparison. The result depends on whether the references point to the same object, not just on the text. Use equals when you need to compare string contents.
Comparing safely when a reference may be null
Calling a method on null causes a NullPointerException. This is an error that stops normal execution unless the program handles it. For example, if name is null, calling name.equals("Java") causes this error.
Java provides Objects.equals for comparisons where either reference might be null. It returns true if both are null, and false if only one is null. Otherwise, it uses the first object’s equals method.
Save this program as NullSafeDemo.java:
import java.util.Objects;
public class NullSafeDemo {
public static void main(String[] args) {
String name = null;
String other = "Java";
System.out.println(Objects.equals(name, other));
System.out.println(Objects.equals(name, null));
System.out.println(Objects.equals(other, "Java"));
System.out.println("Java".equals(name));
}
}The output is:
false
true
true
falseThe last comparison is also safe because the method is called on the non-null string "Java", not on name. For a String, comparing against null with equals returns false.
What does `equals` compare?
A class describes a kind of object and its behavior. The String class defines equals to compare text. Other classes can define equality differently.
A class can also leave equals with its default behavior. In that case, equals checks whether the two references identify the same object. Do not assume that every class compares its contents. Check the class’s documentation when the meaning of equality matters.
For example, an array is an object that holds a group of values. Calling equals on an array checks whether it is the same array, not whether its values match. To compare the contents of two one-dimensional arrays, use Arrays.equals.
Save this program as ArrayEqualityDemo.java:
import java.util.Arrays;
public class ArrayEqualityDemo {
public static void main(String[] args) {
int[] first = {1, 2};
int[] second = {1, 2};
System.out.println(first == second);
System.out.println(first.equals(second));
System.out.println(Arrays.equals(first, second));
}
}The output is:
false
false
trueThe arrays are separate objects, but they contain matching values in the same order.
Choosing a comparison
| Question | Usual choice |
|---|---|
| Do these references point to the same object? | `first == second` |
| Is this reference `null`? | `first == null` |
| Do two non-null strings have the same text? | `first.equals(second)` |
| Are two values equal when either may be `null`? | `Objects.equals(first, second)` |
| Do two one-dimensional arrays have equal contents? | `Arrays.equals(first, second)` |
For objects other than strings, check what their equals method means. Value equality is useful only when the class defines the value you intend to compare.
Exercises
Exercise
Two separate String objects both contain "cat". What do reference equality and String value equality return?
Show answer
== returns false because they are separate objects. equals returns true because their text matches.
Exercise
If first and second are both null, what does Objects.equals(first, second) return?
Show answer
It returns true. It handles two null references without calling a method on null.
Exercise
Two separate int arrays both contain 4 and 5 in that order. Which comparison checks their contents?
Show answer
Arrays.equals(first, second) checks their contents and returns true.