Interview kitsBlog

Your dream job? Lets Git IT.
Interactive technical interview preparation platform designed for modern developers.

XGitHub

Platform

  • Categories

Resources

  • Blog
  • About the app
  • FAQ
  • Feedback

Legal

  • Privacy Policy
  • Terms of Service

© 2026 LetsGit.IT. All rights reserved.

LetsGit.IT/Categories/Java
Javaeasy

In Java, what’s the difference between `==` and `.equals()`?

Tags
#equals#reference#string
Back to categoryPractice quiz

Answer

`==` compares references for objects (same instance), while `.equals()` compares logical equality as defined by the class (e.g., `String` compares content). For primitives, `==` compares values.

String a = new String("hi");
String b = new String("hi");

System.out.println(a == b);       // false
System.out.println(a.equals(b));  // true

Advanced answer

Deep dive

For primitives (`int`, `long`, `boolean`), `==` compares values.

For reference types (`String`, `Integer`, your classes), `==` checks *identity* (same object), while `.equals()` checks *logical equality* (same content/state), as implemented by the class.

Practical rules

  • Use `.equals()` for comparing object values.
  • Use `==` when you explicitly want identity (singletons, enums) or when comparing primitives.
  • Use `Objects.equals(a, b)` when either side can be null (null-safe).

Examples

Integer a = 128, b = 128;
System.out.println(a == b);        // often false (different objects)
System.out.println(a.equals(b));  // true

String s1 = "hi";
String s2 = new String("hi");
System.out.println(s1 == s2);     // false
System.out.println(s1.equals(s2));// true

Common pitfalls

  • Assuming `==` works for `String` content (it’s about references).
  • Calling `a.equals(b)` when `a` may be null (NPE).
  • If you override `equals()`, you must also override `hashCode()` (HashMap/HashSet rely on both).

Related questions

Java
StringBuilder vs StringBuffer: what’s the difference?
#java#string#performance
Java
Why must `equals()` and `hashCode()` follow a contract?
#equals#hashcode#hashmap
Java
String vs StringBuilder vs StringBuffer — when to use which?
#string#stringbuilder
#performance
Java
Why is String immutable in Java?
#string#immutability#memory
Algorithms
KMP string search: how does the LPS/prefix table avoid re-checking characters?
#kmp#string#pattern-matching