1

Having the following code:

String s="JAVA";
for(i=0; i<=100; i++)
     s=s+"JVM";

How many Strings are created? My guess is that 103 Strings are created:

1: the String "JAVA" in the String pool

1: the String "JVM" also in the String pool

101: the new String s is created every time in the loop because the String is an Immutable class

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Adamos2468
  • 151
  • 1
  • 9

3 Answers3

3

String concatenation is implemented through the StringBuilder(or StringBuffer) class and its append method. String conversions are implemented through the method toString, defined by Object and inherited by all classes in Java. For additional information on string concatenation and conversion, see Gosling, Joy, and Steele, The Java Language Specification.

In your case, 103 strings are created, one for each in the loop and the two Strings Java and JVM.

Anindya Dutta
  • 1,972
  • 2
  • 18
  • 33
  • The JLS states that string concatenation *may be* implemented using StringBuilder. It does not state that it is required to be implemented that way. – Stephen C Feb 14 '17 at 12:04
1

When using '+' operator on string, JAVA replace it by a StringBuilder each time.

So for each loop you create a StringBuilder that concat the two strings (s and JVM) with the method append() then its converted to a String by the toString() method

Jérèm Le Blond
  • 645
  • 5
  • 23
1

Compile-time string expressions are put into the String pool. s=s+"JVM" is not a compile-time constant expression. so everytime it creates a new string object in heap.

for more details see this Behavior of String literals is confusing

Community
  • 1
  • 1
Darshan
  • 447
  • 3
  • 17