字符串对象和字符串文字的区别 [英] Difference between string object and string literal

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

问题描述

String str = new String("abc");

String str = "abc";

推荐答案

当您使用字符串字面量时,字符串可以是 实习,但是当您使用 new String("...") 时,您会得到一个新的字符串对象.

When you use a string literal the string can be interned, but when you use new String("...") you get a new string object.

在这个例子中,两个字符串字面量都指向同一个对象:

In this example both string literals refer the same object:

String a = "abc"; 
String b = "abc";
System.out.println(a == b);  // true

这里创建了 2 个不同的对象,它们有不同的引用:

Here, 2 different objects are created and they have different references:

String c = new String("abc");
String d = new String("abc");
System.out.println(c == d);  // false

通常,您应该尽可能使用字符串文字表示法.它更易于阅读,并且让编译器有机会优化您的代码.

In general, you should use the string literal notation when possible. It is easier to read and it gives the compiler a chance to optimize your code.

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

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