condition ? expressionIfTrue : expressionIfFalse
condition:boolean 表達式。expressionIfTrue/False:**類型必須兼容** (可賦值給同一目標類型),三元表達式整體有類型。a ? b : c ? d : e 等價於 a ? b : (c ? d : e)。int score = 85;
String level = score >= 90 ? "優秀" : score >= 60 ? "及格" : "不及格";
// 等價於
String level = score >= 90 ? "優秀" : (score >= 60 ? "及格" : "不及格");
| 情況 | 結果類型 | 示例 |
|---|---|---|
| 兩邊同類型 | 該類型 | int ? 1 : 2 → int |
| 一邊基本類型,一邊包裝類 | 基本類型 (自動拆箱) | true ? 1 : Integer.valueOf(2) → int (NPE 風險!) |
| 兩邊不同基本類型 | 高精度類型 (二元數值提升) | true ? 1 : 2.0 → double |
| 兩邊引用類型 | 公共父類/接口 | true ? "s" : new StringBuilder() → Serializable |
| 一邊 null | 另一邊類型 | true ? "s" : null → String |
// 錯誤:+ 優先級高於 ?:
int x = 10;
String s = "值:" + x > 5 ? "大" : "小"; // 編譯錯誤:String + int → String,無法比較 > 5
// 正確:加括號
String s = "值:" + (x > 5 ? "大" : "小");
口訣:三元運算符優先級**極低**,僅高於賦值運算符,混合運算**務必加括號**。
if-else 或 switch。String result = condition1 ? value1
: condition2 ? value2
: condition3 ? value3
: defaultValue;
val != null ? val : defaultVal (Java 8+ 可用 Optional.ofNullable(val).orElse(defaultVal))。expensive() ? a : b 不會執行 b。if-else 字節碼,無性能差異。三元運算符是「單行 if-else」,用於**簡單、純、類型兼容**的值選擇。複雜邏輯請用 if-else,**可讀性第一**。