1

Following is my code.

public class ShortCkt {

    public static void main(String[] args) {
        int i = 0;
        boolean t = true;
        boolean f = false, b;
        b = (t || ((i++) == 0));// why the value of i does not gets increased?
        b = (f || ((i += 2) > 0));
        System.out.println(i);
    }

}

Output : 2

Why the output is 2 and not 3?

rns
  • 1,047
  • 10
  • 25

2 Answers2

4

Because the || operator operates as a short-circuit if the first operand is true.

Since the first operand is true (t == true), the second condition (that increments i) is not evaluated.

In the second case, the first operand f is false, hence the second operand is evaluated and i gets incremented by 2, ending with value 0 + 2 == 2.

This differs from the && operator, which requires both operands to be evaluated.

The bitwise operators & and | also evaluate both operands when used in boolean conditions.

Summary

  • b = (t || ((i++) == 0)); // b = true OR... whatever, just true
  • b = (t | ((i++) == 0)); // b = true bitwise or 0 == 0 == true (postfix increment, so i gets incremented after evaluation --> true
  • b = (t | ((++i) == 0)); // b = true bitwise or 0 == 0 == true (prefix increment, so i gets incremented before evaluation --> false
  • b = (t && ((++i) == 0)); // b = true AND 1 == 0 == false (prefix increment, so i gets incremented before evaluation --> false
  • b = (t & ((++i) == 0)); // b = true bitwise and 1 == 0 == false (prefix increment, so i gets incremented before evaluation --> false
Mena
  • 47,782
  • 11
  • 87
  • 106
  • how did you get such a deep knowledge? – rns Sep 16 '15 at 13:17
  • 1
    @rns haha actually by mistyping a few operators across a whole class and seriously messing up an android app prototype once, right before latest built was demoed to management. **Now** I can laugh of it. – Mena Sep 16 '15 at 13:19
3

((i++) == 0)) is never evaluated, since t is true and || is a short circuited OR operator, so the second (right) operand is only evaluated if the first (left) operand is false.

In (f || ((i += 2) > 0)), both operands are evaluated, since f is false. Therefore i is incremented from 0 to 2.

Eran
  • 387,369
  • 54
  • 702
  • 768