现在的位置: 首页 > 综合 > 正文

字符串相等(==)的全测试

2013年07月07日 ⁄ 综合 ⁄ 共 1425字 ⁄ 字号 评论关闭
  1. package p1;
  2. /**
  3.  * 字符串相等(==)的全测试。
  4.  * 
  5.  * @author XT Zang,老紫竹
  6.  */
  7. class TestString1 {
  8.   public static void main(String[] args) {
  9.     String hello = "Hello", lo = "lo";
  10.     System.out.print((hello == "Hello") + " "); // true
  11.     System.out.print((Other.hello == hello) + " "); // true
  12.     System.out.print((p2.Other.hello == hello) + " "); // true
  13.     System.out.print((hello == ("Hel" + "lo")) + " "); // true
  14.     System.out.print((hello == ("Hel" + lo)) + " "); // false
  15.     System.out.println(hello == ("Hel" + lo).intern()); // true
  16.   }
  17. }
  18. class Other {
  19.   static String hello = "Hello";
  20. }
  1. package p2;
  2. public class Other {
  3.   public static String hello = "Hello";
  4. }

结论:

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.csdn.net/ZangXT/archive/2008/10/11/3057471.aspx

抱歉!评论已关闭.