Why Does == Fail While equals() Succeeds in Java? Master the Difference

This guide explains the fundamental distinction between Java's == operator and the equals() method, covering primitive vs. reference comparisons, default implementations, common pitfalls like string interning and Integer caching, and the essential contract with hashCode for reliable object equality.

Selected Java Interview Questions
Selected Java Interview Questions
Selected Java Interview Questions
Why Does == Fail While equals() Succeeds in Java? Master the Difference

Key Concepts

The == operator and the equals() method are among the most frequently asked topics in Java interviews. == compares references (memory addresses), while equals() compares content (logical equality). Interviewers often probe deeper using string constant pools, Integer cache, and other nuances.

1. The == Operator

==

is a relational operator that directly compares the values of two operands.

For primitive types (int, double, char, etc.), it compares the literal values.

For reference types (objects, arrays, strings), it compares the two reference variables' heap memory addresses.

int a = 10;
int b = 10;
System.out.println(a == b); // true, primitive values compared directly

String s1 = new String("hello");
String s2 = new String("hello");
System.out.println(s1 == s2); // false, distinct heap objects

2. The equals() Method

equals()

is defined in java.lang.Object. Its default implementation is equivalent to ==:

public boolean equals(Object obj) {
    return this == obj;
}

Many standard library classes override equals() to compare object content instead of address, e.g., String, Integer, List, etc.

String s1 = new String("hello");
String s2 = new String("hello");
System.out.println(s1.equals(s2)); // true, content compared

3. String Constant Pool Pitfalls

String s1 = "hello"; // literal, placed in constant pool
String s2 = "hello"; // reuses the same pool object
String s3 = new String("hello"); // forces a new heap object
System.out.println(s1 == s2); // true, same pool reference
System.out.println(s1 == s3); // false, different heap object
System.out.println(s1.equals(s3)); // true, content equal

The intern() method can move a heap string into the constant pool, making == return true, but such usage is discouraged in production code for readability reasons.

4. Overriding equals() Requires hashCode()

Java's contract states: if two objects are equal according to equals(), they must return the same hashCode(). Failing to do so leads to bizarre bugs in hash‑based collections like HashMap and HashSet.

public class User {
    private String name;

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof User)) return false;
        User u = (User) o;
        return Objects.equals(name, u.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name); // consistent with equals
    }
}

High‑Frequency Follow‑up Questions

Q: What is the result of null == null ? A: true. Both references are the same special null value.

Q: What happens with null.equals(...) ? A: It throws a NullPointerException. Use "constant".equals(variable) or Objects.equals(a, b) to avoid this.

Q: Why does new Integer(127) == new Integer(127) evaluate to false while Integer.valueOf(127) == Integer.valueOf(127) evaluates to true ? A: Integer.valueOf() caches values in the range –128 to 127 (via IntegerCache), returning the same object for repeated calls. new Integer() always creates a new heap object.

Interview Answer Template

== compares memory addresses (or literal values for primitives). equals() is a method from Object that, by default, also uses == , but many classes override it to compare content. Use equals() or Objects.equals() for object comparison, and always override hashCode() together with equals() to maintain the contract required by hash‑based collections.
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

OperatorinterviewequalityhashCodeString poolequals method
Selected Java Interview Questions
Written by

Selected Java Interview Questions

A professional Java tech channel sharing common knowledge to help developers fill gaps. Follow us!

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.