Search code examples
javaternary

return (n > 2) ? n = 5 : n = 4; doesn't work?


Why does this return an error

return (n > 2) ? n = 5 : n = 4;

but this does not

return (n > 2) ? n = 5 : n + 4;

Should it not be able to return n depending on either case?


Solution

  • The code you have can't be compiled because the ternary operator has a higher operator precedence than the assignment operator:

    Operator Precedence

    1. postfix (expr++ expr--)
    2. unary (++expr --expr +expr -expr ~ !)

    ...

    1. ternary (? :)
    2. assignment (= += -= *= /= %= &= ^= |= <<= >>= >>>=)

    When parsing the code

    (n > 2) ? n = 5 : n = 4;
    

    it will parse it like this:

    (n > 2) ? n = 5 : n     // ternary operator
                        = 4 // assignment operator
    

    This would result in pseudo code like this:

    someResultValue 
                    = value;
    

    That will not work and you get compile errors like:

    'Syntax error on token "=", <= expected'

    or

    'Type mismatch: cannot convert from Object & Comparable<?> & Serializable to int'.

    You can use parentheses to let java see the third argument of the ternary operator as n = 4. The code would look like this:

    return (n > 2) ? n = 5 : (n = 4);