- package p1;
- /**
- * 字符串相等(==)的全测试。
- *
- * @author XT Zang,老紫竹
- */
- class TestString1 {
- public static void main(String[] args) {
- String hello = "Hello", lo = "lo";
- System.out.print((hello == "Hello") + " "); // true
- System.out.print((Other.hello == hello) + " "); // true
- System.out.print((p2.Other.hello == hello) + " "); // true
- System.out.print((hello == ("Hel" + "lo")) + " "); // true
- System.out.print((hello == ("Hel" + lo)) + " "); // false
- System.out.println(hello == ("Hel" + lo).intern()); // true
- }
- }
- class Other {
- static String hello = "Hello";
- }
- package p2;
- public class Other {
- public static String hello = "Hello";
- }
This example illustrates six points:
-
Literal strings within the same class (§8) in the same package (§7) represent references to the same String object (§4.3.1).相同包,相同类的字符串常量指向相同的字符串对象
-
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 (§15.28) 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.
参考地址:http://blog.youkuaiyun.com/ZangXT/archive/2008/10/11/3057471.aspx