Search code examples
javareturn-typeboolean-expressionshort-circuiting

How is `return <boolean exp> || <Object exp>` a valid return statement for a method that returns an Object?


I was reading a book, and saw this code:

public Animal getWinner(List<Animal> animals) {
    return animals == null || animals.size() == 0 ? null : animals.get(0);
}

The latter expression is fine as it returns an Animal or null. The former expression is puzzling though, as it's just a boolean expression.

I made a test class and called getWinner(null). It returned null. As far as I know, animals == null would be true, the expression would short-circuit, and I expect the method to return true instead of null.

How does this line compile, and even work as expected?


Solution

  • This has to do with operator precedence in Java and which operator - the boolean or the ternary, will be executed first.

    The ternary has lower precedence, so the or will be evaluated first, meaning it would look like this with parenthesis:

    return (animals == null || animals.size() == 0) ? null : animals.get(0);
    

    So the result of the entire line is either to return null or return animals.get(0).