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

My friend sent me a question he saw in one mock exam for the Java certification about string objects:

String makeStrings(){

String s = "HI";

s = s + "5";

s = s.substring(0,1);

s = s.toLowerCase();

return s.toString();

}

How many string objects will be created when this method is invoked?

The correct answer the exam gave was 3. But I think it's five.

"HI"

"5"

"HI5"

"H"

"h"

Am I wrong?

解决方案

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

}

With respect to the concatenation, when creating a new String,JVM uses StringBuilder, ie:

s = new StringBuilder(s).append("5").toString();

toString() for a StringBuilder is:

public String toString() {

return new String(value, 0, count); //so a new String is created

}

substring creates a new String object unless the entire String is indexed:

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() does NOT create a new String:

public String toString()

{

return this;

}

toLowerCase() is a pretty long method, but suffice it to say that if the String is not already in all lowercase, it will return a new String.

Given that the provided answer is 3, as Jon Skeet suggested, we can assume that both of the String literals are already in the String pool. For more information about when Strings are added to the pool, see Questions about Java's String pool.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值