简体   繁体   中英

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 eg 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 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.

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!

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