daniel451
daniel451

Reputation: 10992

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?

Upvotes: 4

Views: 623

Answers (2)

Persixty
Persixty

Reputation: 8579

You should think of ^ as bitwise XOR.

You should think of booleans as single bits with false=0 and true=1.

That second sentence has as much to do with your question as it does to do with thinking like a programmer!

Upvotes: 0

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 279910

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.

Upvotes: 7

Related Questions