Thursday, December 3, 2026 | London 10°C · Drizzle
DailyGlimpse

AI

Understanding == vs. equals() in Java: A Comprehensive Guide

KSR Datavizon 2 min read

In Java, comparing objects and primitives is a fundamental concept that often confuses beginners. The == operator and the equals() method serve different purposes, and knowing when to use each is crucial for writing bug-free code.

The == Operator

The == operator compares references for objects and values for primitives. For example:

int a = 5;
int b = 5;
System.out.println(a == b); // true, because primitive values are compared

String str1 = new String("Hello");
String str2 = new String("Hello");
System.out.println(str1 == str2); // false, because they reference different objects

The equals() Method

The equals() method is used to compare the contents of objects. By default, it behaves like == (comparing references), but many classes override it to compare actual data. For instance:

String str1 = new String("Hello");
String str2 = new String("Hello");
System.out.println(str1.equals(str2)); // true, because the content is the same

Key Differences

  • Primitives: Always use ==. equals() cannot be used with primitives.
  • Objects: Use == to check if two references point to the same object; use equals() to check logical equality.
  • String Comparison: Always use equals() to compare string contents. Using == may accidentally work due to string interning but is unreliable.

Best Practices

  • Override equals() in your custom classes to define logical equality.
  • Always follow the contract of equals(): reflexive, symmetric, transitive, consistent, and non-null.
  • When overriding equals(), also override hashCode() to maintain consistency.

Understanding this distinction helps avoid subtle bugs and makes your Java code more robust.

React