Question

System.out.print("a".replace('a','1')=="a".replace('a','1'));

true was expected as replace() returns String and String comparison is possible with ==. But the above code prints false. Explanations?

Était-ce utile?

La solution

== checks if they are the same object in memory, so at the same location.

Since these are two distinct strings that just happen to have the same content you need to compare with .equals which compares values not reference.

Autres conseils

No, string comparison is not advisable with ==. In certain cases e.g.:

new String("test") == new String("test")

it returns false.

All this is because theoretically Java should search for certain string in string pool, but in practice there are operations that returns new object instead of the one that resides in string pool.

This is very important to always use "equals" method instead of ==!!

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top