问题
Could you pls explain on the below code:
I know that ==
compares the reference and not the values .
But I am not clear what exactly is happening on the below code?
public class StringEquals {
public static void main(String args[])
{
String s1="AB";
String s2="AB"+"C";
String s3="A"+"BC";
if(s1==s2)
{
System.out.println("s1 and s2 are equal");
}
else
{
System.out.println("s1 and s2 are notequal");
}
if(s2==s3)
{
System.out.println("s2 and s3 are equal");
}
else
{
System.out.println("s2 and s3 are notequal");
}
if(s1==s3)
{
System.out.println("s1 and s3 are equal");
}
else
{
System.out.println("s1 and s3 are notequal");
}
}
}
回答1:
In Java, ==
checks if two objects are exactly same thing, sometime it acts not what you think.
String s1 = new String("AB")
String s2 = new String("AB")
Although s1
and s2
have the same content, but s1 == s2
returns false
. Because they have different reference, But s1 s2
have same value so s1.equals(s2)
returns true
回答2:
On my system, the code prints
s1 and s2 are notequal
s2 and s3 are equal
s1 and s3 are notequal
If your question is why, it has to do with how the Java compiler treats String literals.
Usually, Java will point all references to the same string literal to the same object, for efficiency. In the case of s2
and s3
, the compiler appears to have realized that the result of the concatenation is the same string literal, so it assigned the references s2
and s3
to point at the same object in memory. That is why those two compare equal with ==
.
Since s1
does not have the same value as s2
and s3
, it will be assigned a different memory location, so the reference will not compare equal with ==
.
回答3:
In your code you will likely output System.out.println("s2 and s3 are equal");
This is due to string interning. When the string is a compile time constant the JVM sets all the references to identical strings to the same object. This is an efficiency saving and the java standard does not oblige the JVM to do so, it only allows it to. You should never rely on this behaviour.
Because at compile time it was known that both "AB"+"C"
and "A"+"BC"
will evaluate to "ABC" it was possible to set both s2
and s3
to refer to a single string in the string pool.
It goes without saying that even if this works in some cases it is a dangerous road to go down and strings should always be compared using string.equals(otherString)
来源:https://stackoverflow.com/questions/23673038/string-handling-usage-of