Search code examples
javaconditional-operatoroperator-precedence

Java Operator Precedence and Ternary Operator


The code

return "Unexpected Error: " + (e.getMessage() == null ? "No further details!" : e.getMessage());

produces my expected result. For example, for an e IndexOutOfBoundsException, I get

Unexpected Error: Index 0 out of bounds for length 0

However when I remove the extra parentheses surrounding the ternary expression like

return "Unexpected Error: " + e.getMessage() == null ? "No further details!" : e.getMessage();

I get

Index 0 out of bounds for length 0

I am unable to understand the order of evaluation.

Java Version 1.8.0_341-b10 (64 bit)


Solution

  • The operator, + has higher precedence than the operator, ==

    Therefore

    return "Unexpected Error: " + e.getMessage() == null ? "No further details!" : e.getMessage()
    

    is evaluated as follows:

    if ("Unexpected Error: " + e.getMessage() == null)
        return "No further details!";
    else
        return e.getMessage();
    

    whereas

    return "Unexpected Error: " + (e.getMessage() == null ? "No further details!" : e.getMessage());
    

    is evaluated as

    if (e.getMessage() == null)
        return "Unexpected Error: " + "No further details!";
    else
        return "Unexpected Error: " + e.getMessage();
    

    I hope it clears your doubt.