Question

I have this expression in the if else statement

if (row % 2 == 0 && col % 2 == 0 || row % 2 == 1 && col % 2 == 1) {
    return 0;
}
else {
    return 1;
}

which behaves as intended, returning 0 when the row and column are either both even or both odd. What perplexes me is how Java didn't read it as

(row % 2 == 0 && (col % 2 == 0 || row % 2 == 1 && col % 2 == 1))

How exactly does Java evaluate a statement without parenthesis?

Was it helpful?

Solution

How exactly does Java read a statement without parenthesis?

By applying the operator precedence rules. The Java language specification says that && has a higher precedence than ||, and that means that:

    row % 2 == 0 && col % 2 == 0 || row % 2 == 1 && col % 2 == 1

is equivalent to:

    (row % 2 == 0 && col % 2 == 0) || (row % 2 == 1 && col % 2 == 1)

And in fact, == has a higher precedence than &&, so that is equivalent to:

    ((row % 2 == 0) && (col % 2 == 0)) || ((row % 2 == 1) && (col % 2 == 1))

This page from the Java Tutorial provides more information on operator precedence and how it affects expression evaluation.


For what it is worth, there is a natural parallel between operator precedence in a programming language and the meaning of simple arithmetical expressions ... as you were taught in primary school. For example, you were taught that 1 + 2 x 3 means the same thing as 1 + (2 x 3); i.e. the answer is 7 and not 9. In technical terms, the x (multiplication) operator has higher precedence than the + (addition) operator.

The idea is the same in a typical programming language, except that there is a larger range of operators to deal with ... and the rules are (generally speaking) more precisely specified1.

1 - For instance, since the evaluation of primaries and operators can in some cases have side effects, it can be important to know the precise order in which the sub expressions get evaluated.

OTHER TIPS

That is because of the precedence order. && has precedence over ||.

Look here.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top