String s = "hello";
String s1 = "he";
String s2 = "llo";
String s3 = "he" + "llo";
String s4 = s1 + s2;我明白s == s3是true.因为指向的是同一个字符串常量"hello".
但是为什么s4 == s是false呢?为什么又产生一个对象"hello"呢?不是内存中已经有了"hello"吗?这样的的话s4不是相当于String s4 = new String("hello")了吗?

解决方案 »

  1.   

    这应该是java构造字符串的法则引起的,因为s,s3都是常量构造.而s4是由对象构造而来,所以就新建一个对象了咯.对java的字符串,用==本身就不合理的.
    比较应该用类内的equals()方法!
      

  2.   

    String对象使用"+"时,编译器会自动创建StringBuffer.
    ^_^举个例子:
    String a = b + c 会变成StringBuffer tmp = new StringBuffer();
    tmp.append(b);
    tmp.append(c);
    String a = tmp.toString();
    看了你就明白了为什么s4 == s是false了.
      

  3.   

    interhanchi(路曼曼其修远兮,吾将上下而求索.) 说的很对!
      

  4.   

    为什么s4 == s是false呢?
    == 比较的是引用地址是否相同,不是具体对象啊
      

  5.   

    什么叫不是具体对象
    要不比地址、要不比内容,
    interhanchi(路曼曼其修远兮,吾将上下而求索.) 都说了,显然两个地址是不一样的
      

  6.   

    practical java第一4章(Performance), 实践31有讲, String用来表示那些建立后就不再改变的字符序列.StringBuffer用来表示内容可变的字符序列,提供有一些函数来修改底部字符序列的内容.
    所以String做加法运算时,会被转化成
    StringBuffer tmp = new StringBuffer();
    tmp.append(b);
    tmp.append(c);
    String a = tmp.toString();
      

  7.   

    回复人: interhanchi(路曼曼其修远兮,吾将上下而求索.) 正解
      

  8.   

    看了 interhanchi(路曼曼其修远兮,吾将上下而求索.) 的解释后我反而不懂那为什么s == s3是true了。
      

  9.   

    shxchenwind(秋风扫落叶) 说的对 
     
    因为s,s3都是常量构造.而s4是由对象构造而来,所以就新建一个对象、用==比较的是 对象的引用是否相同
    用equals()比较的是 对象内容是否相同
      
    s == s3 --> s == "hello" --> true
    s == s4 --> s == new String("hello") --> false