2017-10-08 7 views
0
String a = "x"; 
String b = a + "y"; 
String c = "xy"; 
System.out.println(b==c); 

なぜそれが印刷されるのですかConcatの場合のインターンの仕組み

「xy」(+ "y")はインターンされ、変数cが作成されるとコンパイラはリテラル "xy"が存在するかどうかチェックします。 〜にc。

注:私はequals()vs ==演算子を要求していません。

+0

' "XY"'抑留されていますが、 'A +」の結果だが続いたJava

class Test { public static void main(String[] args) { String hello = "Hello", lo = "lo"; System.out.print((hello == "Hello") + " "); System.out.print((Other.hello == hello) + " "); System.out.print((other.Other.hello == hello) + " "); System.out.print((hello == ("Hel"+"lo")) + " "); System.out.print((hello == ("Hel"+lo)) + " "); System.out.println(hello == ("Hel"+lo).intern()); } } class Other { static String hello = "Hello"; } 

でインターン文字列に例が発見されました'a'は最終的なものではないので、結果として' 'xy ''は使用されません。 –

+1

[Javaでファイナル宣言された==の文字列を比較する]の可能な複製(https://stackoverflow.com/questions/19418427/comparing-strings-with-which-are-declared-final-in-java) – Ravi

+0

他の答え:また、それに頼ることを避けてみてください。コードが再利用されると壊れる。 – eckes

答えて

0

cに割り当てられている"xy"が、文字列プール(internが使用)に追加されたのは、値がコンパイル時にわかっているためです。

a+"y"は、コンパイル時には分かりませんが、実行時にのみ認識されます。 internは高価な操作なので、開発者が明示的にコード化しない限り、通常は実行されません。

+0

reply.Okに感謝します。したがって、変数bはスタックに存在します。ここで、cは文字列定数プールを参照していますか? –

+0

技術的には、 'b'はヒープにある文字列を参照します。 –

1

文字列が2つの文字列を連結して形成されている場合、その文字列も包含されます。ここで

String a = "x"; 
String b = a + "y"; // a is not a string literal, so no interning 
------------------------------------------------------------------------------------------ 
String b = "x" + "y"; // on the other hand, "x" is a string literal 
String c = "xy"; 

System.out.println(b == c); // true 

一般的に、それは出力

true 
true 
true 
true 
false 
true 
関連する問題