栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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的字符串池的问题。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/496588.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号