2

Small doubt. Why is the output of the following code 1? Why not 3?

int i = 0;
boolean t = true, f = false, b;
b = (t && ((i++) == 0));
b = (f && ((i+=2) > 0));
System.out.println(i);
Eran
  • 387,369
  • 54
  • 702
  • 768
Leo
  • 5,017
  • 6
  • 32
  • 55

4 Answers4

7

the Conditional-And operator - && - is short circuit. It doesn't evaluate the right operand if the left operand is false. That's why ((i+=2) > 0) is never evaluated, and i remains 1.

From the JLS 15.23:

The && operator is like & (§15.22.2), but evaluates its right-hand operand only if the value of its left-hand operand is true.

Eran
  • 387,369
  • 54
  • 702
  • 768
  • It did not occur to you that this question is a duplicate? – Raedwald Oct 22 '14 at 07:01
  • @Raedwald I don't have time to search for duplicates of questions asked by other people, so I only close as duplicate if I know a specific question that this is a duplicate of. Otherwise, answering often takes much less time. – Eran Oct 22 '14 at 07:04
2

Here is the case

b = (f && ((i+=2) > 0)); // here f is false

Now false && anything is false. && is short circuit operator so it will not evaluate ((i+=2) part since left one is false. So i will remain 1

Just try to change

b = (f && ((i+=2) > 0));

To

b = (f & ((i+=2) > 0));// non short circuit 

Now you will get 3.

That is the two different behavior of short circuit and non short circuit AND.

For more info.

Community
  • 1
  • 1
Ruchira Gayan Ranaweera
  • 34,993
  • 17
  • 75
  • 115
2

Agree with the posted answer as && is responsible for this.

You should note here that your statement b = (t && ((i++) == 0)); is equivalent to

   if(t){
        if(i++==0){
            b=true;
        }
    }

and second statement b = (f && ((i+=2) > 0)); is equivalent to,

  if(f==true){
        i=i+2;
        if(i>0){
            b=true;
        }
   }
akash
  • 22,664
  • 11
  • 59
  • 87
0

For example:

if(p && q){
 // do something
}

if p is evaluated to be false, the rest of the statement need not be evaluated because of the very definition of && (p AND q must be true). If p is not true, then the statement cannot possibly be true.

Aaron C
  • 343
  • 2
  • 9