java对象常量池,Java字符串常量池 - 创建的对象数

How many string objects will be created by the following code?

String s = "Mahendra" + "Singh" + "Dhoni";

Will it create 4 string objects in the string pool or will it create more than that? Please explain in detail.

P.S. I have seen other examples and they deal only for 2 string objects.

EDIT : I see from the answers that in above case only 1 object will be created. Thanks a lot for some very good suggestions. Sorry to ask a stupid question but can you please tell in the below case how many objects will be created?

String s = "Mahendra";

s = s + "Singh" + "Dhoni";

2nd EDIT : Sorry again but I still have some doubt. I see in the comments that in the above case 3 objects will be created "Mahendra", "SinghDhoni" and "MahendraSinghDhoni". My doubt is shouldn't it be calculated from the left to right. Am I missing something - concept wise? Please help.

Also, in another case, if I twist this question, how will the number of objects change. I am asking this as in detail to clear it for lot of my colleagues as well. All the help is appreciated.

String s = "Singh";

s = "Mahendra" + s + "Dhoni";

解决方案

If your code was :

public static void main(String[] args) {

String s = "Mahendra" + "Singh" + "Dhoni";

System.out.println(s);

}

Look at the byte code :

public static void main(java.lang.String[]);

descriptor: ([Ljava/lang/String;)V

flags: ACC_PUBLIC, ACC_STATIC

Code:

stack=2, locals=2, args_size=1

0: ldc #16 // String MahendraSinghDhoni --> This line

2: astore_1

3: getstatic #18 // Field java/lang/System.out:Ljav

/io/PrintStream;

6: aload_1

7: invokevirtual #24 // Method java/io/PrintStream.prin

ln:(Ljava/lang/String;)V

10: return

As you see the compiler is adding All three strings during compile time. So there will be only one string on the String constants pool thats all.

EDIT : based on the edited question :

"Singh" + "Dhoni" will be added during compile time. So there will be totally 3 String objects.

"Mahendra" and "SinghDhoni" will be on String constants pool and then

mahendraSinghDhoni will be on heap.

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值