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

2
  • jit may try replacing it with an arraylist of chars until s is referenced for used Commented Feb 14, 2017 at 10:17
  • @huseyintugrulbuyukisik - 1) AFAIK, it won't ... in an release of Java so far. 2) According to a strict reading of JLS 15.18.1, the JIT compiler is not permitted to do that. Commented Feb 14, 2017 at 12:03

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

The JLS states that string concatenation may be implemented using StringBuilder. It does not state that it is required to be implemented that way.
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

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.