I have some questions about the XOR operator ^ in Java.
I always thought that Java does not have a logical XOR operator because several people told me ^ is bitwise. Today I found some (unconfirmed) posts (without sources) saying ^ is overloaded in Java, working as a logical XOR for booleans and as a bitwise XOR e.g. for integers.
Which statement is true? Can anyone provide some reliable sources?
If ^ is overloaded, which types does it accept?
The Java Language Specification defines
When both operands of an operator
&
,^
, or|
are of a type that is convertible (§5.1.8) to a primitive integral type, binary numeric promotion is first performed on the operands (§5.6.2).The type of the bitwise operator expression is the promoted type of the operands.
- For
^
, the result value is the bitwise exclusive OR of the operand values.
and
When both operands of a
&
,^
, or|
operator are of typeboolean
orBoolean
, then the type of the bitwise operator expression isboolean
. In all cases, the operands are subject to unboxing conversion (§5.1.8) as necessary.
- For ^, the result value is
true
if the operand values are different; otherwise, the result isfalse
.
There is no concept of overloading operators in Java.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With