Java bitwise operators with example

This tutorial will discuss Java bitwise operators with examples.

Like many other operators, Java defines several bitwise operators as well. They can be applied to the integer types, long, int, short, char, and byte to perform the bit-level operation.

Bitwise operators: Following are the bitwise operators.

  • Bitwise OR (|)
  • Bitwise AND (&)
  • Bitwise XOR (^)
  • Bitwise Complement (~)

These operators work with integer data types only. However, the computer understands the binary number system, hence to perform any operation bitwise operators require the given integer in form of binary internally. So to understand these operator understandings of conversion to binary number is a must.

Let’s take a brief overview of the binary conversion. Binary number work on base-2. where any number will be represented in the form of zero and one. The easiest way to convert any number into binary is to divide the number by 2 as binary numbers work on base 2 and keep track of the reminder. Once the division is completed write the reminder in the backward direction. The last reminder will be the first digit.

Consider the following example where we will convert 7 into binary.

binary conversion of 7

Let’s try another number 25.

binary conversion of 25

1. Bitwise OR (|): This operator operates on two operands. It compares corresponding bits of two operands, if either of the bit is one (1) it gives one otherwise zero (0).

12 = 00001100 (in binary)
| 25 = 00011001 (in binary)

--------------------------
00011101 (in binary) = 29 ( in decimal)
----------------------------------------

2. Bitwise AND (&): This operator also operates on two operands. It compares corresponding bits of two operands, if both the bits are one (1) it gives one otherwise zero (0).

12 = 00001100 (in binary)
& 25 = 00011001 (in binary)

---------------------------------
00011101 (in binary) = 21 ( in decimal)
---------------------------------------

3. Bitwise XOR (^): This operator also operates on two operands. It compares corresponding bits of two operands, It gives one if corresponding bits are different otherwise zero. It works in contrast to Bitwise OR (|) operators.

12 = 00001100 (in binary)
^ 25 = 00011001 (in binary)

---------------------------------
00010101 (in binary) = 29 ( in decimal)
---------------------------------------

4. Bitwise Complement (~): This operator operates on only one operand. It inverts every bit pattern zero to one and vice versa.

The unary bitwise complement operator “~” inverts a bit pattern; it can be applied to any of the integral types, making every “0” a “1” and every “1” a “0”. For example, a byte contains 8 bits; applying this operator to a value whose bit pattern is “00000000” would change its pattern to “11111111”.

Recommended Read

Object oriented programming with Java
Class loaders in Java, types of the class loader

Happy Learning !!