Search code examples
javabit-manipulationxor

Java XOR Operator questions


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?


Solution

  • 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 type boolean or Boolean, then the type of the bitwise operator expression is boolean. 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 is false.

    There is no concept of overloading operators in Java.