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

  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

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值