Possible Duplicate:
String comparison and String interning in Java
I have small doubt regarding String comparisons in Java, consider the following code:
if("String".replace('t','T') == "String".replace('t','T')) {
System.out.println("true");
}
else {
System.out.println("false");
}
The above code always print’s false, where as if I try like this:
if("STring" == "STring") {
System.out.println("true");
}
else {
System.out.println("false");
}
It will always print me true. Yes, I know String comparisons should be done with String.equals() or equalsIgnoreCase() method. But this is one of the question was asked in interview and I am confused. Can anyone guide me on this behavior?
As per my knowledge, in code snippet 1, "String.replace('t','T') is returning object, so object comparisons returns in false. Am I right?
Yes, as for this case, you are right.
String#replace(or any method of String class for that matter), will return a new String object (You can guess why? Immutability). And thus you would have to do the comparison usingequalsmethod, to compare their contents.Now, in the second case: –
You are comparing two string literals. Now, since String literals are interned in Java, so both the literals are same (in the sense, they point to the same memory location), and hence
==comparison gives youtrue.The difference in comparison using
==andequalsis that,==compares the reference value – i.e value of memory location of objects, which will be different for two different string objects, as you are having in first case. Whereas,equalscompares the actual content in those objects.