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.)
The code
String s="abc"+"xyz";
creates one String literal at compile time. Java has always done this. It did not change in Java 5.0.
What did change is that if you have code like this
String abc = "abc";
String s = abc + "xyz";
In Java 1.0 to 1.4 it used StringBuffer to do this. It was replaced in Java 5.0 with StringBuilder as it is more efficient if you don't need thread safety and in 99.9% of cases, you don't.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With