else
部分永遠不會達到的,因爲編譯器已經知道第一個條件if(true)
就一定會執行。
在java中,任何不可達的代碼都會導致編譯錯誤。
這是更好JLS§14.21. Unreachable Statements
解釋下這是一個編譯時錯誤,如果不能執行的語句,因爲它是不可達。
編譯器是在這種情況下,很聰明,如果你把它轉換成下面的代碼,然後它永遠不會給你這個錯誤
boolean flag = true
if(flag){
b.Text = "X";
}else{
b.Text = "O";
}
現在試試這個:
int x=5;
if (false) { x=3; } // same Dead code
我可以張貼額外的例子嗎? - 向Down-voter詢問
上面的JLS部分有更多解釋。
下面是一個例子:
while(true){
System.out.println("hello");
}
System.out.println("bye"); // this line is in problem
現在使用相同的標誌,但使其final
final boolean flag = true;
while(flag){
System.out.println("hello");
}
System.out.println("bye"); // still this line is in problem
// because compiler knows that final variable never be changed once assigned
因爲你'if'條件始終評估爲'真'。 –