-1

Case 1:

boolean t=true;
boolean f= false,b;

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

System.out.println(i); // prints i=1

Case 2:

boolean t=true;
boolean f= false,b;

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

System.out.println(i); // prints i=3
Joffrey
  • 32,348
  • 6
  • 68
  • 100

3 Answers3

3

case 1 : (f && ((i+=2)>0 --> f is false, so second statement will not be executed.

case 2 :you are not using binary && , you are using bitwise &, so, i=i+2 will be executed. So result is 3.

TheLostMind
  • 35,966
  • 12
  • 68
  • 104
0

This is because when you use logical and (&&) and the first operand is false, then the other operand is not evaluated.

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

here the (i+=2) never happens.

When you do a bitwise and (&), both operands are evaluated. (i+=2) is executed, hence the different result. To learn more about operators in Java, read: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html

Bartek Maraszek
  • 1,404
  • 2
  • 14
  • 31
0

& = arithmetic AND

&& = logical AND

in this code

`b=(t & ((i++)==0));

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

i is incremented

In the code

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

a "short circuit" is preformed.

f is false for so the rest of the equation does not need to be calculated so i is not increased by 2.

MoMo
  • 111
  • 1
  • 7