Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the output different in case of &&, &, ||?

Tags:

java

operators

Here is the code segments

Can you explain why outputs are varying

1)

public static ShortCkt {
    public static void main(String args[]) {
        int i = 0;
        boolean t = true;
        boolean f = false, b;
        b = (t && ((i++) == 0));
        b = (f && ((i+=2) > 0));
        System.out.println(i);      
    }
}

output in this case is 1

2)

public static ShortCkt {
    public static void main(String args[]) {
        int i = 0;
        boolean t = true;
        boolean f = false, b;
        b = (t & ((i++) == 0));
        b = (f & ((i+=2) > 0));
        System.out.println(i);      
    }
}

output in this case is 3

3)

public static ShortCkt {
    public static void main(String args[]) {
        int i = 0;
        boolean t = true;
        boolean f = false, b;
        b = (t || ((i++) == 0));
        b = (f || ((i+=2) > 0));
        System.out.println(i);      
    }
}

output in this case is 2

4)

public static ShortCkt {
    public static void main(String args[]) {
        int i = 0;
        boolean t = true;
        boolean f = false, b;
        b = (t | ((i++) == 0));
        b = (f | ((i+=2) > 0));
        System.out.println(i);      
    }
}

output in this case is 3

like image 600
Ankit Sachan Avatar asked Aug 09 '10 12:08

Ankit Sachan


1 Answers

Why is the output different in case of &&, &, || ?

Just as in C/C++ && is evaluated "lazily" while & is not.

If a is false then a && b will return false without even evaluating b.

Same goes for a || b: If the first operand, a is true, the whole expression is true and the second operand, b is never evaluated. For a | b however, both a and b will be evaluated.

This has consequences if the operand that's not being evaluated when using && (or ||) has side effects, as in your examples.


Side note: Few java-programmers know that ^ (xor) works for booleans as well. (A ^^ version does not exist simply because it would be redundant.)

like image 96
aioobe Avatar answered Sep 24 '22 02:09

aioobe