字符串对象和字符串文字之间的区别 [英] Difference between string object and string literal
本文介绍了字符串对象和字符串文字之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有什么区别
String str = new String("abc");
和
String str = "abc";
推荐答案
当你使用字符串文字时,字符串可以是< a href =http://en.wikipedia.org/wiki/String_interning =noreferrer> interned ,但是当你使用 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屋!
查看全文