Can anyone explain this strange behavior of String
s?
Here's my code:
String s2 = "hello";
String s4 = "hello"+"hello";
String s6 = "hello"+ s2;
System.out.println("hellohello" == s4);
System.out.println("hellohello" == s6);
System.out.println(s4);
System.out.println(s6);
The output is:
true
false
hellohello
hellohello
You need to be aware of the difference between str.equals(other)
and str == other
. The former checks if two strings have the same content. The latter checks if they are the same object. "hello" + "hello"
and "hellohello"
can be optimised to be the same string at the compilation time. "hello" + s2
will be computed at runtime, and thus will be a new object distinct from "hellohello"
, even if its contents are the same.
EDIT: I just noticed your title - together with user3580294's comments, it seems you should already know that. If so, then the only question that might remain is why is one recognised as constant and the other isn't. As some commenters suggest, making s2
final will change the behaviour, since the compiler can then trust that s2
is constant in the same way "hello"
is, and can resolve "hello" + s2
at compilation time.
"hello" + s2
works like this:
+
operator actually invokes the StringBuilder#append(String s) method"hellohello" == s6
is actually false
.More info:
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