Search code examples
javaconditional-operator

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?


Solution

  • It is simply a nested ternary statement. Clearer by adding parentheses:

    number == null ? (required ? 1 : 2) : 3;
    

    what would the inputs need to be for 2 to be returned?

    number = null and required = false