if 語句是 Java 程式設計中最基礎的流程控制結構,透過布林表達式決定程式執行路徑。掌握其三種形式、代碼塊作用域與常見陷阱,能寫出更健壯、可讀性更高的代碼。
if (布林表達式) {
// 表達式為 true 時執行的語句塊
}
當條件成立才執行特定邏輯,否則直接跳過。
if (布林表達式) {
// true 時執行
} else {
// false 時執行
}
提供互斥的兩條執行路徑,確保一定有一塊會被執行。
if (條件1) {
// 條件1成立
} else if (條件2) {
// 條件1不成立,條件2成立
} else if (條件3) {
// 前兩者不成立,條件3成立
} else {
// 以上條件皆不成立
}
按順序判斷,第一個滿足條件的分支執行後結束整個結構。最後的 else 可省略。
強烈建議永遠保留大括號,即使語句塊只有一行。原因:
int b = 5;
if (b > 4)
System.out.println("b大於4");
else
b--; // 這行是 else 的執行體
System.out.println("b不大於4"); // 這行脫離 if-else,永遠執行!
正確寫法:
if (b > 4) {
System.out.println("b大於4");
} else {
b--;
System.out.println("b不大於4");
}
int c = 5;
if (c > 4)
c--; // 僅這行屬於 if 執行體
System.out.println("c大於4"); // 普通語句
else // 編譯錯誤:else 找不到對應的 if
System.out.println("c不大於4");
Java 不支援 C/C++ 風格的整數隱式轉換,if (age) 會編譯錯誤,必須寫成 if (age > 0)。
可使用 &&(短路與)、||(短路或)合併條件,減少巢狀層級:
// 不推薦:巢狀過深
if (user != null) {
if (user.isActive()) {
if (user.hasPermission("ADMIN")) { ... }
}
}
// 推薦:扁平化
if (user != null && user.isActive() && user.hasPermission("ADMIN")) { ... }
String result = (score >= 60) ? "及格" : "不及格";
適用於單純賦值或回傳場景,過複雜邏輯仍建議用完整 if-else。
>/>=、null 檢查編寫單元測試public class IfDemo {
public static void main(String[] args) {
int age = 25;
boolean hasTicket = true;
// 多條件判斷
if (age >= 18 && hasTicket) {
System.out.println("允許入場");
} else if (age < 18) {
System.out.println("未滿18歲,禁止入場");
} else {
System.out.println("請購買門票");
}
// 巢狀範例(展示大括號必要性)
if (age > 20) {
System.out.println("年齡大於20");
if (hasTicket) {
System.out.println("且持有門票");
}
}
}
}