Possible Duplicate:
If == compares references in Java, why does it evaluate to true with these Strings?
String comparision with logical operator in Java
public static void main(String[] args)
{
String a = "ab";
final String bb = "b";
String b = "a" + bb;
System.out.println(a == b);
}
why it print true??
but,
public static void main(String[] args)
{
String a = "ab";
String bb = "b";
String b = "a" + bb;
System.out.println(a==b);
}
it print false.
You're seeing the result of two things working in combination:
The compiler is processing the "a" + bb
at compile-time rather than runtime, because the bb
is final
and so it knows it can do that. (There are other times it knows that, too.)
All strings generated by the compiler are interned. For more about interning, see this answer to another StackOverflow question about ==
in Java.
So the result is that a
and b
point to the same string instance, and so ==
returns true
.
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