2017-11-24 8 views
-1

false」はどのように返されますか?私が理解から連結された文字列と文字列全体の比較はfalseを返します。

String a = "123"; 
    a = a + "456"; 
    String b = "123456"; 
    System.out.println((a == b)); 

  1. 文字列「123」は文字列プール内に作成し、プールやで作成し、さらに「123456」で作成された「」
  2. 文字列「456」に割り当てられていますプールと 'a'が参照を開始します。
  3. 値「123456」に対して「b」が作成された場合。 JVMはStringプール内の既存のString "123456"を検出し、 "b"もそれを参照します。

したがって、trueを返します。

どこが間違っていますか?

+1

回答は 'A'は'最終的なものならば真であろうと、ここでhttps://stackoverflow.com/a/14123474/2122457 –

+0

です'変数、ええ、' String'プールに格納しますが、これは – SomeJavaGuy

+0

https://stackoverflow.com/questions/45165496/java-string-concatenation-and-interningですか? –

答えて

3

次の行:a = a + "456";は、ヒープ内に新しいオブジェクトを作成し(連結しています)、aに割り当てます。そのため、falseが返されます。 internメソッド(ヒープからプールに文字列を配置する):a.intern() == bを呼び出すと、trueになります。

1

ここではあなたの例では、

String a = "123"; //a reference to "123" in string pool 
a = a + "456"; // Here as you are concatenating using + operator which create a new String object in heap and now a is referencing a string object in heap instead of a string literal in string pool. 
String b = "123456"; // here b is referencing to string pool for "123456" 
System.out.println((a == b)); // This will return false because for the value "123456" a is referencing to heap and b to string pool. Because == operator compare reference rather then values it will return false. 

For more details you can read this page

関連する問題