问题
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
回答1:
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
.
回答2:
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
回答3:
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
来源:https://stackoverflow.com/questions/42223176/how-is-memory-alocated-with-strings-in-java