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

爲什麼要打印false實習生如何在Concat的情況下工作

根據我的理解,「xy」(這是一個+「y」)將被實現,並且當變量c被創建時,編譯器將檢查字符串常量池中是否存在字面值「xy」,如果存在,那麼它將分配相同的引用到c。

注意:我不是要求equals()vs ==操作符。

+0

' 「XY」'被拘留,但結果'A +」因爲'a'不是最終結果,所以y「'不是,也不是實際使用的」xy「結果。 –

+1

可能的重複[比較字符串與在Java中聲明爲最終的==](https://stackoverflow.com/questions/19418427/comparing-strings-with-which-are-declared-final-in-java) – Ravi

+0

此外其他答案:也儘量避免依賴它。如果代碼被重用,它很脆弱。 – eckes

回答

0

原因"xy"被分配到c被直接添加到字符串池(由intern使用)是因爲該值在編譯時已知。

a+"y"在編譯時不知道,但僅在運行時才知道。因爲intern是一項昂貴的操作,除非開發人員明確地對其進行編碼,否則通常不會這樣做。

+0

Thanks for the reply.Ok,所以變量b將出現在堆棧中,因爲c將引用字符串常量池? –

+0

從技術上講,'b'將引用堆中的字符串,否則是。 –

1

如果通過連接兩個字符串文本形成一個字符串,它也將被實現。

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 

這裏是字符串常見的例子在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"; } 

實習,接着它的輸出

true 
true 
true 
true 
false 
true 
相關問題