有什么区别" ABC"和新的字符串(" ABC")?

时间:2014-05-26 09:52:04

标签: java string difference

String str = "ABC"String str = new String("ABC")之间有什么区别?

1 个答案:

答案 0 :(得分:4)

字符串

在Java中Stringspecial object,允许您创建新的String,而必须执行new String("ABC")。但是String s = "ABC"String s = new String("ABC")不是同一个操作。

来自new String(String original)的javadoc:

  

初始化一个新创建的String对象,使其代表   与参数相同的字符序列; [...]

     

除非需要原始的明确副本,否则请使用此构造函数   因为字符串是不可变的,所以是不必要的。

换句话说,执行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的图片。