2015-09-06 55 views
-2

假設我有這樣的代碼爲什麼java在與布爾語句連接時忽略print語句的第一部分?

public class Test{ 
    public static void main (String args[]) { 
     String s = "thrones"; 
     System.out.println("Game of" + "thrones" == s) ; 
    } 
} 

上面的代碼塊的輸出僅僅是 「假」

,但不應該,如果我打印

「的真實遊戲」然而把括號的(「寶座」 == S),其正確

System.out.println("Game of" + ("thrones"==s)); 

打印「的真實遊戲」

我只是好奇它爲什麼沒有在第一個案件中採取打印的第一部分。我只想知道在編譯時發生了什麼。

謝謝。

+0

'1+ 1 == 2'是真的嗎? (或者它會給你一個錯誤,說你不能添加一個int和一個布爾值?)空格被忽略。 – immibis

+2

不應該打印「假」? – Svante

+0

至少2個潛在問題:1.您不使用'=='比較Java中的字符串。 2.你顯然知道你的運算符優先級比我好 - 我會添加一些'()'來明確你的意圖是什麼...... – John3136

回答

1

First, it really prints false,因爲"Game of thrones" != "thrones"

其次,你似乎已經回答了你自己的問題。它解析"Game of" + "thrones" == s("Game of" + "thrones") == s,因爲the + operator has a higher precedence than the == operator

+0

oh ..yes!我沒有意識到這一點! 。它的第一個連接,然後比較。得到它了。謝謝 – shashank

+0

另外,你應該真的使用'String.equals()'方法比較字符串。 –

+0

爲什麼這樣?是不是一樣? – shashank