This week's book giveaways are in the Cloud and AI/ML forums. We're giving away four copies each of Cloud Native Patterns and Natural Language Processing and have the authors on-line! See this thread and this one 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.
String instances are stored in the pool, but StringBuilder and StringBuffer are string-like classes, not String.
s1 and s2 has ...
s1 and s2 points to ....
posted 10 years ago
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.