4

二重引用符を使用して ) 演算子で 2 つの文字列を連結(+し、同じ値を持つ他の文字列リテラルと比較すると、true .. となりますが、2 つの文字列変数を連結して比較すると false になりますか? なぜこれが起こるのですか?

私の知る限り、(+) 演算子で文字列を連結すると、JVM は newStringBuilder(string...).toString()を返します。これにより、ヒープ メモリに新しい String インスタンスが作成され、String プールに 1 つの参照が作成されます。それが真の場合、あるシナリオではtrueを返し、別のシナリオでは false を返す方法は?

最初のシナリオ:

    String string1 = "wel";
    String string2 = "come";
    string1 = string1 + string2; //welcome

    String string3 = "welcome";
    System.out.println(string3 == string1); // this returns false but have same hashcode

2 番目のシナリオ:

    String string4 = "wel" + "come";
    String string5 = "wel" + "come";
    System.out.println(string4 == string5); // this returns true

誰かがこれについて私を助けることができますか?

4

2 に答える 2

4

Please follow comments.

 string1 = string1 + string2; //StringBuilder(string...).toString() which creates a new instance in heap..

 String string3 = "welcome"; // It is not in heap. 

So string3 == string1 false

  String string4 = "wel" + "come"; //Evaluated at compile time

  String string5 = "wel" + "come"; //Evaluated at compile time and reffering to previous literal

So string4 == string5 is true

于 2013-10-21T14:28:18.920 に答える