The Bitwise and Logical Operators

suggest change

The Java language provides 4 operators that perform bitwise or logical operations on integer or boolean operands.

The logical operations performed by these operators when the operands are booleans can be summarized as follows:

A | B | ~A | A & B | A | B | A ^ B | —— | —— | —— | —— | —— | —— | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 1 | 1 | 1 | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 0 | 1 | 1 | 0 |

Note that for integer operands, the above table describes what happens for individual bits. The operators actually operate on all 32 or 64 bits of the operand or operands in parallel.

Operand types and result types.

The usual arithmetic conversions apply when the operands are integers.

Common use-cases for the bitwise operators

The ~ operator is used to reverse a boolean value, or change all the bits in an integer operand.

The & operator is used for “masking out” some of the bits in an integer operand. For example:

int word = 0b00101010;
int mask = 0b00000011;   // Mask for masking out all but the bottom 
                         // two bits of a word
int lowBits = word & mask;            // -> 0b00000010
int highBits = word & ~mask;          // -> 0b00101000

The | operator is used to combine the truth values of two operands. For example:

int word2 = 0b01011111; 
// Combine the bottom 2 bits of word1 with the top 30 bits of word2
int combined = (word & mask) | (word2 & ~mask);   // -> 0b01011110

The ^ operator is used for toggling or “flipping” bits:

int word3 = 0b00101010;
int word4 = word3 ^ mask;             // -> 0b00101001

For more examples of the use of the bitwise operators, see http://stackoverflow.com/documentation/java/1177/bit-manipulation#t=201610101439344327372

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Operators:
* The Bitwise and Logical Operators

Table Of Contents
8 Arrays
10 Maps
11 Strings
25 JAXB
29 Enums
32 Audio
39 Operators
41 Scanner
63 Logging
75 Lists
78 Sets
89 JAX-WS
96 XJC
98 Process
106 Modules
114 Applets
122 JNDI
139 JavaBean
141 Literals
144 Packages
150 JMX
153 JShell
159 Sockets
167 Enum Map
175 Hashtable
177 SortedMap