Search code examples
javafor-loopiterationconditional-statementsshort-circuiting

Java short circuit confusion


This code uses && in the for loop condition. It iterates 4 times resulting in the answer "sum = 20". I would think it iterates 5 times, since the left side of the && condition is true, when the right side becoming false ends the loop.

Basically my question is why does it iterate 4 times and not 5, making the "sum = 30"? Thanks

   `int[] lst = {1,2,3,4,5,4,3,2,1};
    int sum = 0;
    for (int frnt = 0, rear = lst.length - 1;
            frnt < 5 && rear >= 5; frnt++, rear--){
        sum = sum + lst[frnt] + lst[rear];
        System.out.println("frnt: " + frnt);
        System.out.println("rear: " + rear);
        System.out.println();
    }
    System.out.print(sum);`

Solution

  • Short circuiting only happens when the value of the whole expression is already known.

    For the Logical AND operator (&&) if the left hand side is already false, then it does not matter what the right hand side evaluates to because the whole expression is already false. If the left hand side is true, then the value of the right side determines the value of the expression. Since it is not known until it is evaluated, it must be evaluated.

    For the Logical OR operator (||), the reverse is true. If the left side of the expression is true, then it doesn't matter what the right side is, the expression is true, so the right side is not evaluated. If the left side is false, then the value of the expression depends on the right side so it must be evaluated.