Stringstr=”kvill;
Stringstr=newString(“kvill”);的区别:
Strings0=”kvill”;
Strings1=”kvill”;
Strings2=”kv”+“ill”;
System.out.println(s0==s1); // 结果是 True
System.out.println(s0==s2); // 结果也是 True
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:
packagetestPackage;
classTest...{
publicstaticvoidmain(String[]args)...{
Stringhello="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());
}
}
classOther...{staticStringhello="Hello";}
packageother;
publicclassOther...{staticStringhello="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.
本文探讨了Java中字符串常量池的工作原理,通过实例解释了字符串常量如何被存储和引用,以及不同字符串创建方式之间的区别。文章还介绍了字符串字面量在编译期间的处理方式,并对比了运行时字符串连接的行为。

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



