Skip to content
Advertisement

Mixing short-circuit operators with other operators

Assume the following expression:

public class OperatorTest {

public static void main(String[] args) {
    int x = 0;
    int y = 0;

    if(0 == 0 || ++y == 1) {
        // Some other logic here
    }

    System.out.println(y);
}

}

The output is 0. I understand short-circuit operators, in that the right-hand side of || would not execute because the left-hand side evaluates to true. However, ++ takes precedence over short-circuit logical operators, so shouldn’t the ++ operator evaluate before the logical operator is evaluated? Note: I probably would not need to do this in the real-world; this is for a certification exam that I’m studying for.

Advertisement

Answer

The short-circuiting logical operators don’t even evaluate the right side when short-circuiting. This is covered by the JLS, Section 15.24, which covers the || operator.

At run time, the left-hand operand expression is evaluated first; if the result has type Boolean, it is subjected to unboxing conversion (ยง5.1.8).

If the resulting value is true, the value of the conditional-or expression is true and the right-hand operand expression is not evaluated.

(bold emphasis mine)

So, the ++y is never evaluated, and y remains 0.

The same short-circuiting behavior exists for the && operator when the left side evaluates to false.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement