I was trying to evaluate following:
System.out.println(""+(3!=3 | 2==2 | 3==1));
- Returns TRUE System.out.println(""+(3!=3 & 2==2 & 3==1));
- Returns FALSE System.out.println(""+(3!=3 ^ 2==2 ^ 3==1));
- Returns TRUE - How and Why? My Understanding:
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
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
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 istrue
if both operand values aretrue
; otherwise, the result isfalse
.For
^
, the result value istrue
if the operand values are different; otherwise, the result isfalse
.For
|
, the result value isfalse
if both operand values arefalse
; otherwise, the result istrue
.
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.