Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

string

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?

like image 546
soumitra chatterjee Avatar asked Dec 26 '22 09:12

soumitra chatterjee


2 Answers

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.)

like image 139
Jon Skeet Avatar answered Feb 13 '23 04:02

Jon Skeet


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.

like image 41
Peter Lawrey Avatar answered Feb 13 '23 04:02

Peter Lawrey