Wiki Markup |
---|
The conditional operator ? : uses the boolean value of one expression to decide which of the two other expressions should be evaluated, see \[[JLS Section 15.25, Conditional Operator ? :|http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.25]\]. |
The conditional operator is syntactically right-associative. For instance a?b:c?d:e?f:g is equivalent to a?b:(c?d:(e?f:g)).
Format:unmigrated-wiki-markup
{{ConditionalExpression:}}
{{ConditionalOrExpression}}
{{ConditionalOrExpression ? Expression : ConditionalExpression}} \[[JLS Section 15.25 Conditional Operator ? :|AA. Java References#JLS 05]\]ConditionalExpression:
ConditionalOrExpression
ConditionalOrExpression ? Expression : ConditionalExpression
- If the value of the first operand is true, then the second operand expression is chosen
- If the value of the first operand is false, then the third operand expression is chosen
The rules that define the resultant type are given below, where the first match, starting from the top, is used. In the table, * refers to constant expressions of type int
(such as '0' or variables declared as final):
Operand 2 | Operand 3 | Resultant type |
---|---|---|
type T | type T | type T |
boolean | Boolean | boolean |
Boolean | boolean | boolean |
null | reference | reference |
reference | null | reference |
byte or Byte | short or Short | short |
short or Short | byte or Byte | short |
byte,short,char | const int* | byte,short,char if value of int representable |
const int* | byte,short,char | byte,short,char if value of int representable |
Byte | const int* | byte if int is representable as byte |
const int* | Byte | byte if int is representable as byte |
Short | const int* | short if int is representable as short |
const int* | Short | short if int is representable as short |
Character | const int* | char if int is representable as char |
const int* | Character | char if int is representable as char |
other numeric | other numeric | promoted type of the 2nd and 3rd operands |
T1 = boxing conversion (S1) | T2 = boxing conversion(S2) | apply capture conversion to lub(T1,T2) |
...
Wiki Markup |
---|
\[[JLS 05|AA. Java References#JLS 05]\] [Section 15.25, Conditional Operator ? :|http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.25] \[[Bloch 05|AA. Java References#Bloch 05]\] Puzzle 8: Dos Equis |
...