-3
class BoolArray  {
    boolean [] b = new boolean[3];

    int count = 0;

    void set(int i) 
    {
        b[i] = true;
        ++count;
    }

    public static void main(String [] args) 
    {
        BoolArray ba = new BoolArray();
        ba.set(0);
        ba.set(2);
        ba.test();
    }

    void test() 
    {
        if ( b[0] && b[1] | b[2] )
           count++;
        if ( b[1] && b[(++count - 2)] )
           count += 7;
        System.out.println("count = " + count);
    }
}

in all these scenarios,

if ( b[0] && b[1] | b[2] )

if ( b[1] && b[0] || b[2] )

if ( b[1] && b[0] || b[2] )

Why the short circuit logic of '&&' not working as the code is reaching inside the if block?

Please explain also in what order logical operators are executed.

luk2302
  • 55,258
  • 23
  • 97
  • 137
Anuj Kumar Soni
  • 192
  • 2
  • 7
  • *"why the short circuit logic of '&&' not working"* - I can guarantee you it is working as expected. The actual expectation may differ from *your* expectation though. What do you expect to happen instead of what is happening? – luk2302 Dec 30 '17 at 16:18
  • As your code (and the first result on google) shows, the order is first && then ||. Shortcut does not change the outcome of boolean logic. – NickL Dec 30 '17 at 16:27
  • What do you expect your code to do? What does your code actually do? i.e. What output do you expect and what output do you get? Your code is a lot more complex than it needs to be to demonstrate your problem - can you reduce your code down to a [mcve]? – Bernhard Barker Dec 30 '17 at 16:30
  • 1
    Related: [Effect of a Bitwise Operator on a Boolean in Java](https://stackoverflow.com/a/18386156) (unless that `|` was supposed to be `||`) – Bernhard Barker Dec 30 '17 at 16:44
  • Please read [mcve] and enhance your question accordingly. And you want us to spend our time to help you with your problem so you please react to the feedback you get here. – GhostCat Dec 30 '17 at 17:01

1 Answers1

0

Why the short circuit logic of '&&' not working as the code is reaching inside the if block?

The short circuit logic is working just fine. count is 3 before you get to the second if statement, and it correctly doesn't process the ++count and leaves it at 3.

Please explain also in what order logical operators are executed.

The order is:

bitwise AND &
bitwise exclusive OR ^
bitwise inclusive OR |
logical AND &&
logical OR ||

D M
  • 1,410
  • 1
  • 8
  • 12