<分区>
String str = "ABC"
和 String str = new String("ABC")
有什么区别?
标签 java string difference
<分区>
String str = "ABC"
和 String str = new String("ABC")
有什么区别?
最佳答案
在 Java 中 String
是一个 special object并允许您创建一个新的 String
而无需 necessary new String("ABC")
。但是 String s = "ABC"
和 String s = new String("ABC")
不是同一个操作。
来自 new String(String original)
的 javadoc :
Initializes a newly created String object so that it represents the same sequence of characters as the argument; [...]
Unless an explicit copy of original is needed, use of this constructor is unnecessary since Strings are immutable.
换句话说,String s = new String("ABC")
创建了一个新的 String
实例,而 String s = "ABC"
重复使用 String Constant Pool 的实例(如果可用) .
字符串常量池是放置对String
对象的引用集合的地方。
String s = "prasad"
只有在没有其他可用引用时才会创建一个新引用。您可以通过使用 ==
轻松看到这一点运营商。
String s = "prasad";
String s2 = "prasad";
System.out.println(s == s2); // true
图片取自 thejavageek.com .
new String("prasad")
总是创建一个新引用,换句话说,下面示例中的 s
和 s2
将具有相同的值,但不会是相同的对象。
String s = "prasad";
String s2 = new String("prasad");
System.out.println(s == s2); // false
图片取自 thejavageek.com .
关于java - "ABC"和新字符串 ("ABC"之间有什么区别)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23867424/