使用new运算符的String对象数 [英] How many String objects using new operator

查看:113
本文介绍了使用new运算符的String对象数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我们使用new运算符创建一个String对象时,我读到创建了两个对象,一个Object是字符串常量池,第二个是堆内存。

When we use new operator to create a String object, I read that two Objects are created one Object is string constant pool and second one is in heap memory.

我的问题是我们正在使用new运算符,因此只应在Heap中创建一个对象。为什么然后必须在String Constant池中创建另外一个对象。我知道只要我们不使用new运算符来创建String,Java就会存储String对象。例如:

My question here is We are using new operator hence only one object should be created in Heap. Why then one more object has to be created in String Constant pool. I know Java stores String object whenever we not use new operator to create a String. For eg:

String s = "abc" . 

在这种情况下,它只会在String常量池中创建。

In this case only it will create in String constant pool.

String s2 = new String("abc") 

只有一个对象可以在堆中创建,而不是在常量池中。

only one object hast to be created in heap and not in Constant pool.

请解释我为什么错在这里。

Please explain why I am wrong here.

推荐答案


我们正在使用new运算符,因此只应在堆中创建一个对象。

We are using new operator hence only one object should be created in Heap.

当然 - new 操作只创建一个对象。但它的参数是一个String文字,它已经代表了一个对象。每次使用String文字时,都会在类加载期间为其创建一个对象(除非在其他地方已经使用了相同的文字)。这不会被跳过,因为您之后使用该对象作为 new String()操作的参数。

Sure - the new operation only creates one object. But its parameter is a String literal, which already represents an object. Any time you use a String literal, an object was created for that during class loading (unless the same literal was already used elsewhere). This isn't skipped just because you then use the object as a parameter for a new String() operation.

正因为如此,新的String()操作在大多数情况下是不必要的,很少使用。

And because of that, the new String() operation is unnecessary most of the time and rarely used.

这篇关于使用new运算符的String对象数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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