Java字符串常量池 - 创建的对象数 [英] Java String Constant Pool - Number of Objects Created

查看:272
本文介绍了Java字符串常量池 - 创建的对象数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码将创建多少个字符串对象?

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

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

它会在字符串池中创建4个字符串对象还是会创建更多?请详细解释。

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

P.S。我已经看过其他的例子,他们只处理2个字符串对象。

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

编辑:我从答案中看到,在上面的情况下,只会创建1个对象。非常感谢一些非常好的建议。很抱歉问一个愚蠢的问题,但是你可以在下面的情况下告诉你将创建多少个对象吗?

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";

第二次编辑:再次抱歉,但我仍有疑问。我在评论中看到,在上面的例子中,将创建3个对象Mahendra,SinghDhoni和MahendraSinghDhoni。 我怀疑不应该从左到右计算。我错过了什么 - 概念明智吗?请帮忙。

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";


推荐答案

如果你的代码是:

public static void main(String[] args) {
    String s = "Mahendra" + "Singh" + "Dhoni";
    System.out.println(s);
}

查看字节代码:

 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.

编辑:基于编辑问题:

编译时期间将添加Singh+Dhoni 。所以总共会有3个String对象。
MahendraSinghDhoni将在 String constants pool 上然后
mahendraSinghDhoni 将在上。

"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.

这篇关于Java字符串常量池 - 创建的对象数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆