为什么String不需要新的关键字 [英] Why new keyword not needed for String

查看:112
本文介绍了为什么String不需要新的关键字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是java新手。

在java中, String 是一个。但是
我们不必使用 new 关键字来创建类 String 其中 new 用于为其他类创建对象。

In java, String is a class.But we do not have to use new keyword to create an object of class String where as new is used for creating objects for other classes.

我听说过Wrapper类像 Integer Double 这与此类似。
字符串不是Wrapper,不是吗?

I have heard about Wrapper classes like Integer,Double which are similar to this. But String is not Wrapper,isn't it?

实际上当我使用时会发生什么

Actually what is happening when i use

     String message = "Hai";

??
与它有什么不同

?? How it is different from

String message = new String("Hai");

这是消息参考变量或其他什么其他??
还有其他类不需要 new 来创建对象??

Here is message a reference variable or something else?? Are there other classes which do not require new to create object ??

推荐答案

使用以下行,您不是在堆中创建新的 String 对象,而是重用字符串文字(如果已经可用):

With the following line you are not creating a new String object in the heap but reusing a string literal (if already available):

String message = "Hai";

Hai是一个字符串文字字符串文字池。因为,字符串是不可变的,所以它们是可重用的,因此它们由JVM汇集在字符串文字池中。这是推荐的方法,因为你正在重复使用它。

"Hai" is a string literal in the string literal pool. Since, strings are immutable, they are reusable so they are pooled in the string literal pool by the JVM. And this is the recommended way, because you are reusing it.

但是,使用以下内容实际上是在创建一个新对象(在堆中):

But, with the following you are actually creating a new object (in the heap):

String message = new String("Hai");

new String(Hai) is一个新的 String 对象。在这种情况下,即使文字Hai已经在字符串文字池中,也会创建一个新对象。建议不要这样做,因为您可能会以多个具有相同值的 String 对象结束。

new String("Hai") is a new String object. In this case, even if the literal "Hai" was already in the string literal pool, a new object is created. This is not recommended because chances are that you might end with more than one String objects with the same value.

另请参阅此帖子:有关Java字符串池的问题


是否有其他类不需要new来创建对象??

Are there other classes which do not require new to create object ??

实际上,你不能创建任何Java中的对象,不使用关键字 new

Actually, you can not create any object in Java without using the keyword new.

例如

Integer i = 1;

是否,并不意味着整数对象是在不使用 new 的情况下创建的。我们不需要显式使用 new 关键字。但在幕后,如果缓存中不存在值为1的 Integer 对象( Integer 对象缓存为JVM), new 关键字将用于创建它。

Does, not mean that the Integer object is created without using new. It's just not required for us to use the new keyword explicitly. But under the hood, if the Integer object with value 1 does not already exist in cache (Integer objects are cached by JVM), new keyword will be used to create it.

这篇关于为什么String不需要新的关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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