Why does == not work for String comparison in java? [duplicate]

2 weeks ago 22
ARTICLE AD BOX

new String("test") always creates a new object on the heap.

So in:

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

Java creates two different String objects, even though the text is the same.
Therefore:

a == b // false

because == compares references, and a and b point to different objects.

equals() returns true because String overrides it to compare content, not memory location.

Hemant Mhalsekar's user avatar

2 Comments

It is worth noting that from a plain reading of the JLS, a new must create a new object.

2026-01-09T06:39:13.83Z+00:00

(JLS 15.9.4: " The value of a class instance creation expression is a reference to the newly created object of the specified class. Every time the expression is evaluated, a fresh object is created. ")

2026-01-09T06:46:25.543Z+00:00

Read Entire Article