Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What Do Two Question Marks in a Row in a Ternary Clause Mean?

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?

like image 233
Elliptica Avatar asked Dec 15 '20 08:12

Elliptica


People also ask

What does double question mark mean?

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.

What does 2 question marks mean in C#?

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.

Is question mark a ternary operator?

“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.

What is ?: In JS?

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.


1 Answers

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)

like image 188
meriton Avatar answered Sep 16 '22 17:09

meriton