Sub topic 2
== versus equals: identity and equality
This chapter assumes you can write basic Java classes, know the difference between primitives and object references, and have used String, List, and Map. By the end you should be able to predict what == and equals return for strings, boxed numbers, enums, and your own classes, and you should know which one to use.
Two questions about two values
Java gives you two ways to ask whether two values are "the same", and they ask different questions.
- Identity: do both expressions refer to the very same object in memory? The
==operator answers this. - Equality: do the two objects represent the same logical value? The
equalsmethod answers this.
Two separate envelopes can hold identical letters. They are equal in content but not identical as objects. Java keeps the two ideas apart, and many bugs come from mixing them up.
What == compares
The meaning of == depends on the operand types.
| Operand types | What `==` compares |
|---|---|
| Primitives (`int`, `char`, `boolean`, `double`) | The values themselves |
| Object references | Whether both references point to the same object |
For primitives, == is the correct tool. For references, == never looks inside the objects. It only checks whether the two references hold the same address. A new expression always creates a fresh object, so two new results are never ==.
public class IdentityDemo {
public static void main(String[] args) {
String a = new String("hello");
String b = new String("hello");
String c = a;
System.out.println(a == b); // false: two distinct objects
System.out.println(a == c); // true: c refers to the same object as a
System.out.println(a.equals(b)); // true: same character content
}
}Here a == c is true because both variables hold the same reference. a == b is false even though the characters match, because the references differ.
What equals does
equals is an instance method declared in java.lang.Object. Its default implementation does exactly what == does:
public boolean equals(Object obj) {
return (this == obj);
}So unless a class overrides equals, "equal" means "identical". Many classes override it to compare content. String, the wrapper classes such as Integer, and the collections such as List and Set do this.
import java.util.List;
public class DefaultEqualsDemo {
static class Account { }
public static void main(String[] args) {
Account x = new Account();
Account y = new Account();
System.out.println(x.equals(x)); // true: same object
System.out.println(x.equals(y)); // false: Account inherits Object.equals
List<Integer> l1 = List.of(1, 2, 3);
List<Integer> l2 = List.of(1, 2, 3);
System.out.println(l1 == l2); // false: separate objects (not guaranteed by the spec)
System.out.println(l1.equals(l2)); // true: List compares element by element
}
}Whether equals compares content is therefore a property of each class. When you write a class whose instances should compare by value, you must override equals. The next chapter covers the rules that override must follow.
When == looks like it works on strings
String literals are a common source of confusion because == sometimes returns true for them. The Java compiler and JVM keep one shared instance of each string literal in the string pool. Two literals with the same characters refer to the same pooled object.
public class StringPoolDemo {
public static void main(String[] args) {
String a = "hello";
String b = "hello";
String c = new String("hello");
String d = "hel" + "lo"; // compile-time constant, pooled
String part = "hel";
String e = part + "lo"; // computed at run time, new object
System.out.println(a == b); // true: same pooled literal
System.out.println(a == c); // false: new always creates an object
System.out.println(a == d); // true: constant expression
System.out.println(a == e); // false: runtime concatenation
System.out.println(a == e.intern()); // true: intern returns the pooled instance
System.out.println(a.equals(e)); // true
}
}Code that compares strings with == can pass tests with literals and then fail once a string arrives from user input, a file, or a network call. Those strings are created at run time and are not pooled. Always compare string content with equals.
Boxed numbers and the cache
The wrapper classes Integer, Long, Short, Byte, and Character have a similar trap. Autoboxing converts int to Integer through Integer.valueOf, which returns cached objects for values from -128 to 127. Outside that range it normally creates a new object.
public class BoxingDemo {
public static void main(String[] args) {
Integer small1 = 127;
Integer small2 = 127;
Integer big1 = 1000;
Integer big2 = 1000;
System.out.println(small1 == small2); // true: both from the cache
System.out.println(big1 == big2); // false on a default JVM: two objects
System.out.println(big1.equals(big2)); // true: same numeric value
System.out.println(big1 == 1000); // true: big1 is unboxed, then ints are compared
Integer i = 1;
Long l = 1L;
System.out.println(i.equals(l)); // false: different classes
System.out.println(i.longValue() == l); // true: primitive comparison after unboxing
}
}This example shows several rules:
- The cache range is an implementation detail. The upper bound can be raised with a JVM option, so code must not depend on it.
- If one operand of
==is a primitive and the other is a wrapper, Java unboxes the wrapper and compares values. That is whybig1 == 1000is true. Integer.equalsreturns false for aLongargument, becauseequalschecks the argument's class before comparing values.- Comparing an
Integerreference directly to aLongreference with==does not compile.
Use equals when comparing two wrapper objects. Better still, unbox to primitives when you want a numeric comparison.
Null and the order of operands
Calling equals on a null reference throws NullPointerException. == handles null safely. These three forms behave differently when a value may be null:
import java.util.Objects;
public class NullSafetyDemo {
public static void main(String[] args) {
String input = null;
System.out.println(input == null); // true: safe
System.out.println("yes".equals(input)); // false: null argument is allowed
System.out.println(Objects.equals(input, null)); // true: both null counts as equal
System.out.println(Objects.equals(input, "yes")); // false
try {
System.out.println(input.equals("yes"));
} catch (NullPointerException ex) {
System.out.println("NullPointerException");
}
}
}Use == and != to test for null. When a variable might be null, put a known non-null value on the left ("yes".equals(input)), or use Objects.equals(a, b), which returns true if both are null, false if exactly one is null, and otherwise calls a.equals(b).
Cases where == is the right choice
Identity is the correct test in a few situations:
- Primitives. There is nothing else to compare.
- Null checks.
ref == null. - Enums. Each constant exists as exactly one instance in the JVM, so
==is correct and null-safe.Color.RED == colornever throws, whilecolor.equals(Color.RED)does whencoloris null. - Intentional identity checks. For example, asking whether two variables refer to the same mutable object, or a fast path at the start of an
equalsimplementation (if (this == o) return true;).
Floating-point values
Primitive double comparison follows IEEE 754 rules, while Double.equals follows a different rule so that it can work as a consistent hash key.
public class DoubleDemo {
public static void main(String[] args) {
double nan = Double.NaN;
System.out.println(nan == nan); // false
System.out.println(Double.valueOf(nan).equals(nan)); // true
System.out.println(0.0 == -0.0); // true
System.out.println(Double.valueOf(0.0).equals(-0.0)); // false
}
}When your own equals compares double fields, use Double.compare(a, b) == 0 so that it matches Double.equals. A later chapter covers this in detail.
Common errors
- Comparing strings from input, files, or methods such as
substringwith==. - Comparing two
IntegerorLongobjects with==and seeing the result change once values exceed 127. - Calling
equalson a value that may be null. - Assuming a class compares by content without checking whether it overrides
equals. Arrays are a notable case:array1.equals(array2)is identity, and you needArrays.equalsfor content. - Expecting
equalsto work across numeric types, such asIntegerandLong.
Exercise
Given Integer a = 200; Integer b = 200; String s = null;, what do a == b, a.equals(b), and "x".equals(s) print on a default JVM, and why does s.equals("x") behave differently from "x".equals(s)?
Show answer
a == b prints false, because 200 is outside the -128 to 127 cache range, so autoboxing creates two separate objects and == compares references. a.equals(b) prints true, because Integer.equals compares the numeric values. "x".equals(s) prints false, because String.equals accepts a null argument and returns false. s.equals("x") throws NullPointerException, because it calls a method on a null reference.
Exercise
A class Ticket has a field id and does not override equals. What does new Ticket(1).equals(new Ticket(1)) return, and what must you do so that it returns true?
Show answer
It returns false, because Ticket inherits Object.equals, which is the same as == and compares references. To make it return true, override equals(Object) in Ticket to compare the id field, and override hashCode consistently. The following chapters show how.