Search code examples
javaandroidconditional-operatoroperator-precedence

How is the ternary operator under Java (Android)supposed to behave according to the standard?


So how is the Java (@Android) ternary operator supposed to behave really ?

Check these simple examples:

boolean trigger  = true;
String myStr_NOK = trigger  ? "YES:" : "NO:"
                 + " if trigger was TRUE"
                 + " this is NOT visible :-o";

String myStr_OK = (trigger  ? "YES:" : "NO:")
                 + " if trigger was TRUE"
                 + " this is visible as should.";

// I think the first comments missed this fact:
trigger = false;
String myStr_NOK2 = trigger  ? "YES:" : "NO:"
                 + " if trigger was FALSE"
                 + " this IS concatenated AGAIN";

Now I got a bit confused about this logic. It apparently has to do with operator precedence.

See: myStr_NOK only contains "YES:", since the ternary operator was not in brackets ?

Seems like I REALLY have to encapsulate the ternary operator in Java with brackets, otherwise the concatenated string will not get the rest of composed string ?

EDIT: Let me re-phrase my Q: What does the standard say about ternary operator priority ? My observation is such, that withOUT parenthesis around the ternary operator, the further string concatenation is performed ONLY when expression is FALSE. If TRUE, it does not concatenate.

According to this page ternarry operator "?:" has really low priority in Java, similarly like in C++.


Solution

  • It does not misbehave at all.

    Your first example is basically this written out:

    if(true) "YES";
    else "NO" + theOtherStrings;
    

    Your second example is written out like this

    String string;
    if(true) string = "YES";
    else string = "NO";
    string = string + theOtherStrings