5.2 Testing Equality (== vs. .equals())

Key Takeaways

  • Numeric equality uses binary numeric promotion. Boolean equality accepts two primitive booleans or one primitive boolean and one Boolean, 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, and LocalDate have value-based equality contracts. StringBuilder and arrays use Object.equals(), which compares identity.

  • Comparing null == null returns true safely, whereas invoking .equals() on a null reference throws NullPointerException

Last updated: November 2026

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 to double.
  • Else if either is float, the other is converted to float.
  • Else if either is long, the other is converted to long.
  • Otherwise, both operands (including byte, short, char) are promoted to int.
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:

  1. String literals (e.g., "ab") are stored in the String Pool and reused.
  2. new String("ab") explicitly allocates a separate String object with the same contents as the pooled input.
  3. Compile-time constant concatenation ("a" + "b", or final String p = "a"; p + "b") is folded by javac into a single literal "ab" at compile time, so it points to the pooled String.
  4. Runtime concatenation (String s = "a"; s + "b") creates a new String. 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.

Loading diagram...
References to Interned and Distinct String Objects

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.

TypeHas a Value-Based .equals()?a.equals(b) for Distinct ObjectsHow to Compare Contents
StringYestruea.equals(b) (case-sensitive)
Wrapper (Integer, Double, etc.)YesTrue if they have the same wrapper class and meet its value contracta.equals(b). For example, Double.equals distinguishes the two signed zeros.
ArrayListYestrue (same elements & order)list1.equals(list2)
LocalDate / LocalTime / LocalDateTimeYestrued1.equals(d2)
StringBuilder / StringBufferNofalse (different objects)sb1.toString().equals(sb2.toString())
Arrays (int[], String[])Nofalse (different objects)Arrays.equals(arr1, arr2)
Custom class using Object.equalsNofalseOverride 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:

  1. null == null is true. Testing a variable obj == null does not dereference the variable.
  2. After arguments evaluate normally, calling the instance method on a null receiver throws NullPointerException. A compliant implementation of equals returns 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.

Test Your Knowledge

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));
A

true true true

B

false false true

C

false true true

D

true false true

Test Your Knowledge

Which expression evaluates to false?

A

new StringBuilder("ocp").equals(new StringBuilder("ocp"))

B

Arrays.asList(1, 2).equals(Arrays.asList(1, 2))

C

5 == 5.0f

D

LocalDate.of(2026, 5, 1).equals(LocalDate.of(2026, 5, 1))

Test Your Knowledge

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));
A

true true true

B

false false true

C

true true false

D

false true true

Sections you finish are checked off in the contents.