String str=”kvill;
String str=new String (“kvill”);的区别:





Java会确保一个字符串常量只有一个拷贝。
因为例子中的s0和s1中的”kvill”都是字符串常量,它们在编译期就被确定了,所以s0==s1为true;而”kv”和”ill”也都是字符串常量,当一个字符串由多个字符串常量连接而成时,它自己肯定也是字符串常量,所以 s2也同样在编译期就被解析为一个字符串常量,所以s2也是常量池中”kvill”的一个引用。
所以我们得出s0==s1==s2;
在JAVA language specification中的3.10.5 String Literals有相关说明:
the test program consisting of the compilation unit:



















produces the output:
true true true true false true
This example illustrates six points:
• Literal strings within the same class in the same package represent
references to the same String object .
• Literal strings within different classes in the same package represent references
to the same String object.
• Literal strings within different classes in different packages likewise represent
references to the same String object.
• Strings computed by constant expressions are computed at compile
time and then treated as if they were literals.
• Strings computed by concatenation at run time are newly created and therefore
distinct.
The result of explicitly interning a computed string is the same string as any
pre-existing literal string with the same contents.