Interview Q&A / Object-Oriented Programming

BeginnerQuick answer1 min readUpdated 3 Oct 2026

What is the difference between == and equals() in Java?

SHORT ANSWER

== compares references for objects (are they the same object?) and values for primitives. equals() compares content, but only if the class overrides it; the default version behaves like ==.

Explain it simply

Two printed copies of the same train ticket have the same details but are different pieces of paper. == asks "is this the very same paper?". equals() asks "do both papers say the same thing?".

String overrides equals() to compare characters. A class you write does not, until you override it, and then you must also override hashCode().

Example

java
String a = new String("goa");
String b = new String("goa");
System.out.println(a == b);        // prints: false
System.out.println(a.equals(b));   // prints: true

int x = 5, y = 5;
System.out.println(x == y);        // prints: true (primitives, by value)

String literals like "goa" are pooled, so "goa" == "goa" is usually true. Do not rely on that for logic.

What to say in the interview

"For primitives, == compares values. For objects, == compares references, while equals() is meant to compare logical content. The default Object.equals is the same as ==, so I override it, along with hashCode, for value-like classes."

Common mistakes

  • Comparing strings with == in conditions.
  • Overriding equals without hashCode, which breaks HashMap and HashSet.

#java#equals#objects

Related questions

Practise more Object-Oriented Programming questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open Object-Oriented Programming quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.