How many String objects will be created in String s = "abc" + "xyz"; in previous versions of Java 1.5?

According to this link, in Java versions 1.5 String s="abc"+"xyz";only one object is created in the code due to compiler optimization using the StringBuilder class.

new StringBuilder().append(abc).append(xyz).toString()

Does this mean that before java 1.5 String is used to create three objects: one "abc", another "xyz" and the third "abcxyz" OR then it uses some other class, for example StringBuffer, for similar optimization of the compiler?

+4
source share
2 answers

No, as far as I know, it was always considered a compile-time constant and was always equivalent

String s = "abcxyz";

, Java 1.5 StringBuilder; StringBuffer.

JLS, :

- , , , (ยง15.27), "", , String.intern(ยง20.12 0,47).

( 15.27 .)

+6

String s="abc"+"xyz";

. Java . Java 5.0.

, ,

String abc = "abc";
String s = abc + "xyz";

Java 1.0 1.4 StringBuffer. Java 5.0 StringBuilder, , 99,9% .

+4

Source: https://habr.com/ru/post/1539641/


All Articles