0

can anyone tell me why it prints out 1? I know for sure that true and false AND EXCLUSIVE gives 0. why it enters in if statement?

 public static void main(String[] args) {
    boolean a=true, b=false; 
    int i=0; 
    if(a^b)   {
        i++;
    } 
    System.out.print(i++);
 }

thank you!

Andreas Fester
  • 35,119
  • 7
  • 92
  • 115
tziuka
  • 545
  • 1
  • 6
  • 23

5 Answers5

5

You're using xor : ^.

true ^ false == true

See also:

I'm actually not sure what you mean by "exclusive and". See also:

Community
  • 1
  • 1
Lukas Eder
  • 196,412
  • 123
  • 648
  • 1,411
2

xor tables

0^0 == 0
0^1 == 1
1^0 == 1
1^1 == 0

So it enters the if statement.

At the end of your main block, after the System.out.println(i++) the i variable will have the value 2 as currently written

Stephen Connolly
  • 13,565
  • 5
  • 37
  • 61
0

If you talk about ^, it is exclusive or. And for any propositions p1 and p2, p1 ^ p2 is true only if one of p1 or p2 are true.

It is therefore normal that it prints 1.

fge
  • 114,841
  • 28
  • 237
  • 319
0

In Java the ^ operator is bitwise Exclusive OR, not Exclusive AND. Since true XOR false is TRUE, it enters in the if clause.

I'd suggest for you simply to use == and != operators, if you're dealing with boolean.

manub
  • 3,820
  • 2
  • 24
  • 33
  • 2
    In this context it is not the bitwise exclusive or, but the logical exclusive or ;) – fge Jun 17 '13 at 13:31
0

The ^ operator is exclusive or. The truth table for this is

 XOR  | false true 
-------------------
false | false true
true  | true  false

That's why you get "1" - your if statement evaluates to true.

Cheers,

Anders R. Bystrup
  • 15,324
  • 10
  • 61
  • 54