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!

2

5 Answers 5

5

You're using xor : ^.

true ^ false == true 

See also:

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

Sign up to request clarification or add additional context in comments.

3 Comments

But I learnt that XOR gives true only when we have 1 and 1 (true , true) , but in this case we have 1 and 0 (false). isn't?
That's just "AND". As in && or &
T && T == T, T && F == F, T ^ T == F, T ^ F == T
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

Comments

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.

Comments

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.

1 Comment

In this context it is not the bitwise exclusive or, but the logical exclusive or ;)
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,

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.