java - "ABC"和新字符串 ("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

enter image description here

图片取自 thejavageek.com .


new String("prasad") 总是创建一个新引用,换句话说,下面示例中的 ss2 将具有相同的值,但不会是相同的对象。

String s = "prasad";
String s2 = new String("prasad");

System.out.println(s == s2); // false

enter image description here

图片取自 thejavageek.com .

关于java - "ABC"和新字符串 ("ABC"之间有什么区别)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23867424/

相关文章:

Java、字符串差分算法

r - 计算 R 中的重复测量差异

java - 上传到 Google Drive 文件未找到异常

java outOfMemoryError 与 stringbuilder

具有两个字符串的 Python 函数 - 子字谜

JavaScript:搜索字符串时 indexOf 与匹配?

Java, "Variable name"无法解析为变量

java - 参数未在 POST 方法 REST Java 中传递

java - 在 Java 中处理延迟事件的最佳方法是什么

swift - Swift 中的属性闭包和方法有什么区别?