String s = "abc";
这里采用的是一种特殊类型:字串可用加引号的文字初始化。通常,必须为对象使用一种更通用的初始化类型。String s = new String("asdf");
它不仅指出“将我变成一个新字串”,也通过提供一个初始字串,指出了“如何生成这个新字串”。
这里采用的是一种特殊类型:字串可用加引号的文字初始化。通常,必须为对象使用一种更通用的初始化类型。String s = new String("asdf");
它不仅指出“将我变成一个新字串”,也通过提供一个初始字串,指出了“如何生成这个新字串”。
"abc"是内存堆中一个已经存在的对象,这个是声明用s指向这个对象。String s = new String("abc");
"abc"是内存堆中一个已经存在的对象,有没有引用指向它并不知道;这个语句通过new关键字,生成了一个与"abc"对象内容一致的另一个对象(即拷贝了一份),新生成的这个对象用s指向。API中的解释:
String(String original)
Initializes a newly created String object so that it represents the same sequence of characters as the argument; in other words, the newly created string is a copy of the argument string.
而String a="abc";中,由于String是个特殊的类,java编译器遇到带双引号的字符串时,就会自动生成一个实例其实和String a=nwe String("abc"); 是一样的。
我觉得DanaLiu说的很有道理