Difference between == and .equals() in Java

In Java, == and .equals() are both used to compare things — but they compare different aspects of objects.


== (Reference Comparison)

== checks whether two references point to the exact same object in memory.

It does NOT check if the contents are equal.

Example:

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

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

Even though both contain "hello", they are different objects in memory.

However:

String a = "hello";
String b = "hello";

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

Because Java uses the String Pool, both references point to the same object.


.equals() (Content Comparison)

.equals() checks whether two objects are logically equal (same content).

For StringInteger, and many other classes, .equals() is overridden to compare values.

Example:

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

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

Because the contents are the same.


Important Difference Summary

Feature==.equals()
ComparesMemory addressObject content
Works for primitives?✅ Yes❌ No
Works for objects?✅ Yes✅ Yes
Can be overridden?❌ No✅ Yes

Special Case: Primitives

For primitive types (intdoubleboolean, etc.):

int x = 5;
int y = 5;

System.out.println(x == y); // true

== compares actual values.

.equals() cannot be used with primitives.


Important Warning (Null Safety)

String str = null;
str.equals("hello"); // ❌ NullPointerException

Safer way:

"hello".equals(str); // ✅ Safe

Real-World Rule of Thumb

  • Use == for primitives

  • Use .equals() for object value comparison

  • Use == for objects only when you want to check if they are the same instance



Nenhum comentário:

Postar um comentário

HashMap in Java

Let’s break down how   HashMap   works internally (Java 8+ implementation). What Is a HashMap? HashMap<K, V>  is a  hash table–based  ...