0

Below two JAVA codes are printing two different outputs:

    int i = 0;
    boolean t = true;
    boolean f = false, b;
    b = (t | ((i++) == 0));
    b = (f | ((i += 2) > 0));
    System.out.println(i);

Output: 3


    int i = 0;
    boolean t = true;
    boolean f = false, b;
    b = (t || ((i++) == 0));
    b = (f || ((i += 2) > 0));
    System.out.println(i);

Output: 2

What is the reason behind this?

  • `||` does short-circuit evaluation, so `i` doesn't get incremented when the first part of the condition is `true`. – GriffeyDog Dec 19 '17 at 22:18
  • 2
    because they are different... the question is what is the difference between `|` and `||`, right? the second operand of `||` is only executed if needed, that is, if the first operand is not true. With `|` both operands are always executed. Similar with `&` and `&&` - see [Java Language Specification](https://docs.oracle.com/javase/specs/jls/se9/html/jls-15.html#jls-15.24) – user85421 Dec 19 '17 at 22:20
  • 1
    @CarlosHeuberger Thanks. I got it. If I set "t" to "false" in second Code then it will give me output as 3. – Tripti Bishnoi Dec 19 '17 at 23:21

0 Answers0