开发者

What's the difference between String and new String? [duplicate]

开发者 https://www.devze.com 2023-03-09 07:06 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: What is the purpose of the expression “new String(…)” in Java?
This question already has answers here: Closed 11 years ago.

Possible Duplicate:

What is the purpose of the expression “new String(…)” in Java?

What's the diffe开发者_如何学Pythonrence between these two statements:

String a1 = new String("abc");

and

String a2 = "abc";

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


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.

(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.)

0

精彩评论

暂无评论...
验证码 换一张
取 消