As per this link , in java versions 1.5 onward in code String s="abc"+"xyz";
only one object is created due to compiler optimization using StringBuilder class.
new StringBuilder().append(abc).append(xyz).toString()
So does that mean before java 1.5 String used to create three objects one "abc" ,another "xyz" and the third one "abcxyz" OR then it use some other class like StringBuffer for similar compiler optimization?
No, as far as I'm aware that has always been treated as a compile-time constant, and has always been equivalent to
String s = "abcxyz";
Note that Java 1.5 introduced StringBuilder
; before that execution-time string concatenation used StringBuffer
.
Looking at the first edition of the JLS, already the crucial sentence existed:
String literals - or, more generally, strings that are the values of constant expressions (§15.27) are "interned" so as to share unique instances, using the method String.intern (§20.12.47).
(And section 15.27 includes string concatenation.)
See more on this question at Stackoverflow