I recently saw this ternary operation statement in a piece of Java code:
int getVal(Integer number, boolean required) {
Integer val = number == null ? required ? 1 : 2 : 3;
return val;
}
I've never seen a ternary statement with two question marks in a row like that (without any parentheses). If I play with the input values, I can get 1
to return if number == null
and 3
to return otherwise, but it doesn't seem to matter what required is, 2
never gets returned.
What does this statement mean (i.e. how should I read it as a word statement of true
/false
conditions) and what would the inputs need to be for 2
to be returned?
If double question marks are uses it is to emphasise something in return, usually from the shock of the previous thing said. For example, if I said: 'My dog just died' (sad, but used for example...) Someone may reply.
The C# double question mark operator ?? is called the null-coalescing operator. It is used to return the left hand side operand of the operator if the value is not null and the right hand side operand if the value is null.
“Question mark” or “conditional” operator in JavaScript is a ternary operator that has three operands. The expression consists of three operands: the condition, value if true and value if false.
The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark ( ? ), then an expression to execute if the condition is truthy followed by a colon ( : ), and finally the expression to execute if the condition is falsy.
An expression of the form a ? b ? c : d : e
uses the conditional operator twice. The only ambiguity is in which order.
It can not mean (a ? b) ? c : d : e
because that would be a syntax error.
Therefore, it must mean a ? (b ? c : d) : e
.
That is, it is equivalent to:
if (a) {
if (b) {
return c;
} else {
return d;
}
} else {
return e;
}
A more interesting case is
a ? b : c ? d : e
which could be read as
(a ? b : c) ? d : e
or
a ? b : (c ? d : e)
To resolve this ambiguity, the Java language specification writes:
The conditional operator is syntactically right-associative (it groups right-to-left)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With