user3111525
user3111525

Reputation: 5223

Java: Why is it called bitwise exclusive or?

I am trying to understand how bitwise exclusive or works in java. So for example:

false ^ false = false
true ^ true = false  
true ^ false = true 
false ^ true = true

According to some posts here at SO, the size of boolean in java is jvm dependant. Typically boolean may be represented with 32 bits on the stack, 8 bits in the array.

So, why is it called bitwise if it is more than a byte on the stack?

Upvotes: 1

Views: 363

Answers (4)

wolfrevo
wolfrevo

Reputation: 7303

According to the Java Language Specification there is no boolean bitwise operator but only boolean logical operators and integer bitwise operators.

15.22.1. Integer Bitwise Operators &, ^, and |

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 AND of the operand values.

For ^, the result value is the bitwise exclusive OR of the operand values.

For |, the result value is the bitwise inclusive OR of the operand values.

15.22.2. Boolean Logical Operators &, ^, 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 both operand values are true; otherwise, the result is false.

For ^, the result value is true if the operand values are different; otherwise, the result is false.

For |, the result value is false if both operand values are false; otherwise, the result is true.

Upvotes: 7

Andrei Nicusan
Andrei Nicusan

Reputation: 4623

It's called "bitwise" because it applies the logical XOR operation to each pair of bits on corresponding positions in the bit representation of the two operands (which can be any number, not only booleans).

Here's a simplified example for 8 bits:

9 (00001001) ^ 14 (00001110) = 7 (00000111).

Upvotes: 2

user2314737
user2314737

Reputation: 29387

Bitwise refers to the size of the information they represent. Booleans represent 1 bit of information even though they might need more than 1 bit to be saved in memory.

Upvotes: 2

TondaCZE
TondaCZE

Reputation: 2700

The ^ operator is overloaded. So if you use it on primitive boolean values, it work like logical XOR.

Upvotes: 4

Related Questions