문제

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?

도움이 되었습니까?

해결책

== 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.

다른 팁

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 ==!!

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top