简体   繁体   中英

Java: How conditions are evaluated in Bitwise XOR operator ? (^)

I was trying to evaluate following:

  1. System.out.println(""+(3!=3 | 2==2 | 3==1)); - Returns TRUE
  2. System.out.println(""+(3!=3 & 2==2 & 3==1)); - Returns FALSE
  3. System.out.println(""+(3!=3 ^ 2==2 ^ 3==1)); - Returns TRUE - How and Why?

My Understanding:

  1. Will return TRUE; on base of second comparison ( 2==2 ); but it will do all comparisons; unlike || which only do 1 comparison and return result

  2. Will return false; even it gets result during first comparison( 3!=3 ); but it will do all comparisons. Not like && which only do 1 comparison and return result

  3. ? How it evaluates statements?
System.out.println(""+(3!=3 | 2==2 | 3==1));
// System.out.println(""+(false | true | false));
// System.out.println(""+(    true     | false));
// System.out.println(""+(true));
System.out.println(""+(3!=3 & 2==2 & 3==1));
// System.out.println(""+(false & true & false));
// System.out.println(""+(    false    & false));
// System.out.println(""+(false));
System.out.println(""+(3!=3 ^ 2==2 ^ 3==1));
// System.out.println(""+(false ^ true ^ false));
// System.out.println(""+(    true     ^ false));
// System.out.println(""+(true));

Quoting JLS section 15.22.2 , and knowing that expressions are evaluated from left to right:

For & , the result value is true if both operand values are true ; otherwise, the result is false .

For ^ , the result value is true if the operand values are different; otherwise, the result is false .

For | , the result value is false if both operand values are false ; otherwise, the result is true .

As a side-note, the correct names are :

  • & is bit-wise and.
  • | is bit-wise inclusive or.
  • ^ is bit-wise exclusive or.

It is evaluated from left to right :

3!=3 ^ 2==2 is false ^ true which is true.

true ^ 3==1 is true ^ false which is true.

XOR is an "exclusive or statement". How it works generally: Take these 2 binary numbers:

0 0 1 1 0 1
0 1 1 0 1 1
- - - - - - XOR
0 1 0 1 1 0

XOR will only return true if ONE of the two booleans that are compared is true.

So in case of boolean comparison (the logic table):

   ^  |  true | false
----------------------
true  | false | true
----------------------
false | true  | false

In your specific case this means:

( 3!=3  ^ 2==2   ^ 3==1)
((false ^ true)  ^ 3==1)
(       true     ^ 3==1)
(       true     ^ false)
true

It is the Bitwise xor operator in java which results 1 for different value of bit (ie 1 ^ 0 = 1) and 0 for same value of bit (ie 0 ^ 0 = 0) when a number is written in binary form.

First it evaluates (3!=3 ^ 2==2) which is false, Then false(from previous step) ^ false (3==1) is evaluated to true.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM