String makeStrings() {
String s = "HI"; //String literal
s = s + "5"; //concatenation creates new String object (1)
s = s.substring(0,1); //creates new String object (2)
s = s.toLowerCase(); //creates new String object (3)
return s.toString(); //returns already defined String
}
对于串联,创建一个新的字符串时,JVM
使用StringBuilder
,即:
s = new StringBuilder(s).append("5").toString();
toString()
为StringBuilder
是:
public String toString() {
return new String(value, 0, count); //so a new String is created
}
substring
创建一个新的String对象除非整个String
被索引:
public String substring(int beginIndex, int endIndex) {
if (beginIndex < 0) {
throw new StringIndexOutOfBoundsException(beginIndex);
}
if (endIndex > count) {
throw new StringIndexOutOfBoundsException(endIndex);
}
if (beginIndex > endIndex) {
throw new StringIndexOutOfBoundsException(endIndex - beginIndex)
}
return ((beginIndex == 0) && (endIndex == count)) ? this :
new String(offset + beginIndex, endIndex - beginIndex, value);
}
toString()
确实不创建一个新的字符串:
public String toString()
{
return this;
}
toLowerCase()
是一个相当长的方法,但我只想说,如果String
是不已经在全部小写,它将返回一个new String
。
鉴于提供的答案是3
,正如Jon Skeet所建议的,我们可以假定两个字符串字面值已经在字符串池中。有关何时将字符串添加到池中的更多信息,请参阅Questions about Java's String pool。
我怀疑区别在于“HI”和“5”已经在字符串池中,所以它们不会在每个方法调用中创建。 –
@GrijeshChauhan我在SO meta上发了一个[post](http://meta.stackexchange.com/questions/190688/determining-whether-a-post-should-be-marked-as-a-duplicate#190689)。我认为我们应该投票关闭另一个,而不是结束这篇文章。也许我有偏见,但我认为这些答案更好... –
@SteveP。我已投票表决已经重复选项... –