Why in Java you’re able to add Strings with the + operator, when String is a class? In theString.java code I did not find any implementation for this operator. Does this concept violate object orientation?
Why in Java you’re able to add Strings with the + operator, when String
Share
Let’s look at the following simple expressions in Java
The compiler converts
"x = "+x;into aStringBuilderinternally and uses.append(int)to “add” the integer to the string.5.1.11. String Conversion
15.18.1.
The optimized version will not actually do a full wrapped String conversion first.
This is a good illustration of an optimized version used by the compiler, albeit without the conversion of a primitive, where you can see the compiler changing things into a StringBuilder in the background:
http://caprazzi.net/posts/java-bytecode-string-concatenation-and-stringbuilder/
This java code:
Generates this – see how the two concatenation styles lead to the very same bytecode:
Looking at the example above and how the byte code based on the source code in the given example is generated, you will be able to notice that the compiler has internally transformed the following statement
into
In other words, the operator
+in string concatenation is effectively a shorthand for the more verboseStringBuilderidiom.