问题描述
具有以下代码:
String s="JAVA";
for(i=0; i<=100; i++)
s=s+"JVM";
创建了多少个字符串?我的猜测是创建了103个字符串:
How many Strings are created? My guess is that 103 Strings are created:
1:字符串池中的字符串"JAVA"
1: the String "JAVA" in the String pool
1:字符串池中也有字符串"JVM"
1: the String "JVM" also in the String pool
101:因为该字符串是一个不可变的类,所以每次在循环中都会创建新的字符串s
101: the new String s
is created every time in the loop because the String is an Immutable class
推荐答案
字符串连接是通过StringBuilder
(或StringBuffer
)类及其append
方法实现的.字符串转换通过方法toString
实现,该方法由Object
定义并由Java中的所有类继承.有关字符串连接和转换的其他信息,请参见Java语言规范 Gosling,Joy和Steele.
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.
在您的情况下,将创建103个字符串,循环中每个字符串一个,两个字符串Java
和JVM
.
In your case, 103 strings are created, one for each in the loop and the two Strings Java
and JVM
.
这篇关于在Java中如何通过字符串分配内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!