String和new String有什么区别? [英] What's the difference between String and new String?

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

问题描述


可能重复:

表达式的目的是什么?ldquo; new String(…)”在Java?

这两个陈述之间的区别是什么:

What's the difference between these two statements:

String a1 = new String("abc");

String a2 = "abc";

如果你能说明差异,那就太棒了。

If you could illustrate the difference, that would be great.

推荐答案

第一个是创建一个新的String对象;第二个是有效地使用已经存在的(它是在加载类文件时创建的。)几乎没有理由使用 String(String)构造函数。

The first one is creating a new String object; the second one is effectively using one which already exists (it's created while loading the class file.) There is virtually never a reason to use the String(String) constructor.

(我说虚拟,因为有一种情况:如果你打破了巨大的 String 通过调用 substring()然后丢弃原始文件,可以使用此构造函数创建新的 String s来自子字符串。但这确实是一个不起眼的案例。)

(I say virtually because there is one case: if you're breaking up a huge String by calling substring() and then discarding the original, you can save memory by using this constructor to create new Strings from the sub-strings. That's really an obscure case, though.)

这篇关于String和new String有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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