5.2 Testing Equality (== vs. .equals())
Key Takeaways
Numeric equality uses binary numeric promotion. Boolean equality accepts two primitive booleans or one primitive
booleanand oneBoolean, which is unboxed.Between compatible references,
==tests object identity or two null references. The behavior of.equals()follows the method implementation selected for the receiver.Equal string constant expressions share an interned reference. With
String s = "a";,(s + "b") == "ab"is false because the concatenation is computed at run time.String, wrappers,ArrayList, andLocalDatehave value-based equality contracts.StringBuilderand arrays useObject.equals(), which compares identity.Comparing null == null returns true safely, whereas invoking .equals() on a null reference throws NullPointerException
Determine the operand types before applying ==. Numeric or boolean comparisons can unbox a wrapper. Between compatible reference operands, == compares object identity. For .equals(), use the contract of the class that implements the method, including an implementation inherited from a superclass.
Primitive == Comparison and Numeric Promotion
For numeric == and !=, Java applies binary numeric promotion before comparing. This covers two primitive numeric operands and a primitive numeric operand compared with a wrapper that can unbox to a numeric type:
- If either operand is
double, the other is converted todouble. - Else if either is
float, the other is converted tofloat. - Else if either is
long, the other is converted tolong. - Otherwise, both operands (including
byte,short,char) are promoted toint.
System.out.println(5 == 5.0); // true (int 5 promoted to double 5.0)
System.out.println('a' == 97); // true (char 'a' promoted to int 97)
System.out.println('a' == 97.0f); // true (char 'a' promoted to float 97.0f)
System.out.println(true == false); // false (valid boolean == boolean)
// System.out.println(true == 1); // DOES NOT COMPILE: incomparable types
// System.out.println("5" == 5); // DOES NOT COMPILE: String vs int
Important
Java is strictly typed on ==: you cannot compare a boolean with any numeric type, a primitive with an unrelated object type, or two reference operands if neither compile-time type can be cast to the other (for example, String and StringBuilder). An interface reference can be comparable even if the compiler cannot infer which instance it contains.
Wrapper Classes and == vs. .equals()
Mixing a primitive and its wrapper with == triggers unboxing of the wrapper, so Integer.valueOf(500) == 500 evaluates to true. However, comparing two wrapper references with == tests object identity, bringing the Integer cache (-128 through 127) into play:
Integer a = 127, b = 127;
Integer c = 128, d = 128;
System.out.println(a == b); // true (cached Integer objects)
System.out.println(c == d); // not guaranteed by Java SE 8
System.out.println(c.equals(d)); // true (Integer overrides .equals())
Integer i = 5;
Long l = 5L;
// System.out.println(i == l); // DOES NOT COMPILE: Integer vs Long
System.out.println(i.equals(l)); // false (different wrapper classes!)
Notice i.equals(l) compiles because .equals(Object) accepts any Object, and it returns false because Integer.equals checks obj instanceof Integer.
Reference == vs. .equals() and the String Pool
Between compatible reference types, == checks whether the values refer to the same object or are both null. Methods such as String.equals can compare contents by a class-specific rule.
The String Pool associates interned strings with their canonical references:
- String literals (e.g.,
"ab") are stored in the String Pool and reused. new String("ab")explicitly allocates a separateStringobject with the same contents as the pooled input.- Compile-time constant concatenation (
"a" + "b", orfinal String p = "a"; p + "b") is folded byjavacinto a single literal"ab"at compile time, so it points to the pooledString. - Runtime concatenation (
String s = "a"; s + "b") creates a newString. A method call follows the method contract. It is never a string constant expression, even when the receiver and its arguments are literals.
String s1 = "ab";
String s2 = "ab";
String s3 = new String("ab");
String s4 = "a" + "b";
final String f = "a";
String s5 = f + "b";
String v = "a";
String s6 = v + "b";
System.out.println(s1 == s2); // true (both pooled)
System.out.println(s1 == s3); // false (new forces heap allocation)
System.out.println(s1 == s4); // true (compile-time constant folding)
System.out.println(s1 == s5); // true (final constant folded at compile time)
System.out.println(s1 == s6); // false (runtime concatenation creates new object)
System.out.println(s1.equals(s3)); // true (same characters)
System.out.println(s1.equals(s6)); // true (same characters)
Watch one subtle String method edge case: Java SE 8 documents that trim() returns the receiver when no trimming is needed, so "ab".trim() == "ab" is true. The API guarantees the trimmed content of " ab".trim(), but the identity of that result is not needed to compare contents.
Which Java Classes Override .equals()?
In java.lang.Object, the default implementation is simply:
public boolean equals(Object obj) {
return (this == obj);
}
When a non-null receiver uses Object.equals(), equality means identity. A class can inherit a different implementation. For example, ArrayList inherits list equality from AbstractList. Compare that behavior with StringBuilder and arrays, which use identity.
| Type | Has a Value-Based .equals()? | a.equals(b) for Distinct Objects | How to Compare Contents |
|---|---|---|---|
String | Yes | true | a.equals(b) (case-sensitive) |
Wrapper (Integer, Double, etc.) | Yes | True if they have the same wrapper class and meet its value contract | a.equals(b). For example, Double.equals distinguishes the two signed zeros. |
ArrayList | Yes | true (same elements & order) | list1.equals(list2) |
LocalDate / LocalTime / LocalDateTime | Yes | true | d1.equals(d2) |
StringBuilder / StringBuffer | No | false (different objects) | sb1.toString().equals(sb2.toString()) |
Arrays (int[], String[]) | No | false (different objects) | Arrays.equals(arr1, arr2) |
Custom class using Object.equals | No | false | Override equals(Object) and hashCode() consistently when you need value equality |
Trace the difference between String, StringBuilder, ArrayList, and arrays:
StringBuilder sb1 = new StringBuilder("Java");
StringBuilder sb2 = new StringBuilder("Java");
System.out.println(sb1 == sb2); // false
System.out.println(sb1.equals(sb2)); // false!
System.out.println(sb1.toString().equals(sb2.toString())); // true
int[] arr1 = {1, 2, 3};
int[] arr2 = {1, 2, 3};
System.out.println(arr1.equals(arr2)); // false!
System.out.println(Arrays.equals(arr1, arr2)); // true
List<String> l1 = new ArrayList<>(Arrays.asList("A", "B"));
List<String> l2 = new ArrayList<>(Arrays.asList("A", "B"));
System.out.println(l1 == l2); // false
System.out.println(l1.equals(l2)); // true
Warning
Watch out for overloading vs. overriding equals in custom classes! Writing public boolean equals(Person p) overloads equals instead of overriding equals(Object o). With an Object receiver type, a call resolves to equals(Object), and the runtime uses the override of that signature, if any. Standard list element comparisons also use equals(Object); equals(Person) alone will not change them.
null References and NullPointerException
Testing equality when a reference might be null follows two simple rules:
null == nullis true. Testing a variableobj == nulldoes not dereference the variable.- After arguments evaluate normally, calling the instance method on a null receiver throws
NullPointerException. A compliant implementation ofequalsreturns false for a null argument on a non-null receiver.
String input = null;
System.out.println(input == null); // true
System.out.println("admin".equals(input)); // false (safe!)
System.out.println(Objects.equals(input, null)); // true (java.util.Objects null-safe helper)
// System.out.println(input.equals("admin")); // throws NullPointerException!
Placing the literal first ("admin".equals(input)) or guarding with input != null && input.equals("admin") avoids NullPointerException cleanly.
What is the output of the following code?
String a = "java8";
String b = "java";
String c = b + 8;
String d = "java" + 8;
System.out.println((a == c) + " " + (a == d) + " " + a.equals(c));
true true true
false false true
false true true
true false true
Which expression evaluates to false?
new StringBuilder("ocp").equals(new StringBuilder("ocp"))
Arrays.asList(1, 2).equals(Arrays.asList(1, 2))
5 == 5.0f
LocalDate.of(2026, 5, 1).equals(LocalDate.of(2026, 5, 1))
What happens when the following code is compiled and executed?
Integer x = 200;
Integer y = new Integer(200);
int z = 200;
System.out.println((x == y) + " " + (x == z) + " " + x.equals(z));
true true true
false false true
true true false
false true true
Sections you finish are checked off in the contents.