Reputation: 151
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
Upvotes: 1
Views: 122
Reputation: 1982
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
.
Upvotes: 3
Reputation: 457
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
Upvotes: 1
Reputation: 701
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
Upvotes: 1