條件運算子()

句法

{condition-to-evaluation} {statement-executed-on-true} {statement-executed-on-false}

如語法所示,條件運算子(也稱為三元運算子 1 )使用 ?(問號)和:(冒號)字元來啟用兩個可能結果的條件表示式。它可用於替換較長的 if-else 塊,以根據條件返回兩個值中的一個。

result = testCondition ? value1 : value2

相當於

if (testCondition) { 
    result = value1; 
} else { 
    result = value2; 
}

它可以讀作 “如果 testCondition 為 true,則將結果設定為 value1; 否則,將結果設定為 value2“。

例如:

// get absolute value using conditional operator 
a = -10;
int absValue = a < 0 ? -a : a;
System.out.println("abs = " + absValue); // prints "abs = 10"

相當於

// get absolute value using if/else loop
a = -10;
int absValue;
if (a < 0) {
    absValue = -a;
} else {
    absValue = a;
}
System.out.println("abs = " + absValue); // prints "abs = 10"

常見用法

你可以使用條件運算子進行條件賦值(如 null 檢查)。

String x = y != null ? y.toString() : ""; //where y is an object

這個例子相當於:

String x = "";

if (y != null) {
    x = y.toString();
}

由於條件運算子具有第二低的優先順序,在賦值運算子之上,很少需要在條件周圍使用括號,但是當與其他運算子組合時,需要在整個條件運算子構造周圍使用括號 :

// no parenthesis needed for expressions in the 3 parts
10 <= a && a < 19 ? b * 5 : b * 7

// parenthesis required
7 * (a > 0 ? 2 : 5)

條件運算子巢狀也可以在第三部分中完成,其中它更像連結或像 switch 語句。

a ? "a is true" :
b ? "a is false, b is true" :
c ? "a and b are false, c is true" :
    "a, b, and c are false"

//Operator precedence can be illustrated with parenthesis:

a ? x : (b ? y : (c ? z : w))

腳註:

1 - Java 語言規範Java 教程都將(? :)運算子稱為條件運算子。該教程說它也稱為三元運算子,因為它(目前)是 Java 定義的唯一三元運算子。 條件運算子術語與 C 和 C++以及具有等效運算子的其他語言一致。