String str=”kvill;
String str=new String (“kvill”);的区别:
String s0=”kvill”;
String s1=”kvill”;
String s2=”kv” + “ill”;
System.out.println( s0==s1 ); // 结果是 True
System.out.println( s0==s2 ); // 结果也是 TrueJava会确保一个字符串常量只有一个拷贝。
因为例子中的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:
package testPackage;
class Test ...{
public static void main(String[] args) ...{
String hello = "Hello", lo = "lo";
System.out.print((hello == "Hello") + " ");
System.out.print((Other.hello == hello) + " ");
System.out.print((other.Other.hello == hello) + " ");
System.out.print((hello == ("Hel"+"lo")) + " ");
System.out.print((hello == ("Hel"+lo)) + " ");
System.out.println(hello == ("Hel"+lo).intern());
}
}
class Other ...{ static String hello = "Hello"; }
package other;
public class Other ...{ static String hello = "Hello"; }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.

被折叠的 条评论
为什么被折叠?



