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

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

问题描述

我是 Java 新手.

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

我听说过类似 IntegerDouble 之类的 Wrapper 类,它们与此类似.但是 String 不是 Wrapper,不是吗?

实际上我使用时发生了什么

 String message = "Hai";

??它与

有何不同

String message = new String("Hai");

这里是 message 一个引用变量还是别的什么??是否有其他不需要 new 来创建对象的类??

解决方案

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

String message = "Hai";

"Hai" 是字符串字面量池中的字符串字面量.由于字符串是不可变的,它们是可重用的,因此它们被 JVM 合并到字符串文字池中.这是推荐的方式,因为您正在重用它.

但是,通过以下操作,您实际上是在创建一个新对象(在堆中):

String message = new String("Hai");

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

另见这篇文章:关于 Java 字符串池的问题

<块引用>

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

实际上,如果不使用关键字new,您无法在Java 中创建任何对象.

例如

整数 i = 1;

确实,并不意味着 Integer 对象是在不使用 new 的情况下创建的.我们不需要显式使用 new 关键字.但实际上,如果缓存中不存在值为 1 的 Integer 对象(Integer 对象由 JVM 缓存),new 关键字将用于创建它.

I am new in java.

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.

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

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

解决方案

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

Also see this post: Questions about Java's String pool

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

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

e.g.

Integer i = 1;

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 不需要 new 关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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