This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
I'm studing the String chapter and written some code that is not giving the result I expect. What I understood is that when you create a String, if it already present in the pool then that is assigned to your reference.
This is my test code:
I expected s1==s2 to return true, because both the Strings contains "abcdef" so I thought the JVM assigned s1 and s2 to the same String in the pool, but this doesn't seem correct. This is the output of the execution:
s1 = abcdef
s2 = abcdef
s1 and s2 has the same value
shouldn't print this
The Java language provides special support for the string concatenation operator ( + ), and for conversion of other objects to strings. String concatenation is implemented through the StringBuilder (or StringBuffer) class and its append method.
s1 and s2 has ...
s1 and s2 points to ....
Joined: Aug 15, 2008
String concatenation results in a reference to an object of type String, which is a newly created object if the right-hand side expression is not a compile time constant expression.
The right-hand side of assignment in line 1 is not a compile time expression, so the (newly created) object that s3 refers is not the same that s1 refers (the one in the string pool). For this reason s1 == s3 is false, while s1 == s2 is true.