Possible Duplicate:
How do I compare strings in Java?
String s1 = "andrei";
String s2 = "andrei";
String s3 = s2.toString();
System.out.println((s1==s2) + " " + (s2==s3));
Giving the following code why is the second comparison s2 == s3 true ?
What is actually s2.toString() returning ? Where is actually located (s2.toString())
?
First of all String.toString
is a no-op:
/**
* This object (which is already a string!) is itself returned.
*
* @return the string itself.
*/
public String toString() {
return this;
}
Second of all, String constants are interned so s1 and s2 are behind the scenes changed to be the same String instance.
The method String.intern() can be used to ensure that equal strings have equal references. String constants are intern
ed, so s1
and s2
will reference the same string. String.toString()
simply returns itself, that is, a.toString()
returns a, when a is a String. So, s2 also == s3.
In general, strings should not be compared by reference equality, but by value equality, using equals()
. The reason is that it's easy to get two strings that are equivalent but different references. For example, when creating substrings. An exception to this rule is that if you know both strings have been intern
ed beforehand (or you intern them as part of the comparison.)
To answer your implied question about heap or stack, Strings are allocated on the heap. Even if they were allocated on the stack, such as with the upcoming escape analysis and stack allocation, the semantics of the program will not change, and you will get the same result for both heap and stack allocation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With