Java中有多少个字符串对象?

Java中有多少个字符串对象?,第1张

Java中有多少个字符串对象

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
}


关于串联,在创建新的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
不是 已经全部小写,它 返回一个
newString

鉴于所提供的答案是

3
,如JonSkeet所建议的,我们可以假定这两个String文字均已在String池中。有关何时将字符串添加到池中的更多信息,请参见有关Java的字符串池的问题。



欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5488709.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-12-12
下一篇2022-12-12

发表评论

登录后才能评论

评论列表(0条)

    保存