According to the JLS 15.18.1, "If only one operand expression is of type String, then string conversion is performed on the other operand to produce a string at run time." and "A value x of primitive type T is first converted to a reference value as if by giving it as an argument to an appropriate class instance creation expression:"
This seems to say that if you concat a String and a char that it will first Create a Char, call toString() on the char and then do the concat.
However, using javap -c it seems that this is not happening. Also, it takes much longer to concat String += String (because it's creating all those extra objects) than it does to concat String += char.
Can someone explain this to me, please? [ April 19, 2002: Message edited by: Marilyn deQueiroz ]
JavaBeginnersFaq "Yesterday is history, tomorrow is a mystery, and today is a gift; that's why they call it the present." Eleanor Roosevelt
Hi Marilyn, I thought that on all String concatenation, that StringBuffers were used. This is what the javadocs say on StringBuffer: String buffers are used by the compiler to implement the binary string concatenation operator +. For example, the code:
x = "a" + 4 + "c" is compiled to the equivalent of: x = new StringBuffer().append("a").append(4).append("c").toString() Wouldn't += be implemented in a similar way?
Michael Morris SCJP2
Any intelligent fool can make things bigger, more complex, and more violent. It takes a touch of genius - and a lot of courage - to move in the opposite direction. - Ernst F. Schumacher
Regarding the JLS quotes, 184.108.40.206 includes the phrase "as if". It is not required that an intermediate Character object actually be created - it's enough that the subsequent String is the same one that you would have gotten if you had performed new Character(c).toString(). Furthermore, 220.127.116.11 says
An implementation may choose to perform conversion and concatenation in one step to avoid creating and then discarding an intermediate String object. To increase the performance of repeated string concatenation, a Java compiler may use the StringBuffer class or a similar technique to reduce the number of intermediate String objects that are created by evaluation of an expression. For primitive types, an implementation may also optimize away the creation of a wrapper object by converting directly from a primitive type to a string.
So the compiler is actually free to do whatever it deems most efficient here, as long as the final result is the same. [ April 18, 2002: Message edited by: Jim Yingst ]