Bitwise Operators in Java

The Bitwise operators in Java programming are used to perform bit operations. In Java bitwise, all the decimal values will convert into binary values (sequence of bits, i.e., 0100, 1100, 1000, 1001, etc.). The Bitwise Operators will work on these bits, such as shifting them left to right or converting bit value from 0 to 1, etc.

The table below shows the different Java Bitwise operators and their meanings. For example, Consider x = 6 and y = 8 and their values in binary form are

x = 0110

y = 1000

OperatorsMeaningExamples
&ANDX & Y = 0000
|ORX | Y = 1110
^exclusive ORX ^ Y = 1110
~complement~X = 00001001 (The Not operator will convert all 0 into 1). Remember, the Compliment of N will be -(N + 1)
<<Shift leftX << 1 = 00001100 (Bits will move 1 step left. If we use 2 or 3, then they shift accordingly)
>>Shift rightY >> 1 = 00000100

Let us see the Truth Table behind Bitwise Operators in Java Programming Language.

xyx & y X | yx ^ y
00000
01011
10011
11110

Bitwise operators in Java example

This example helps to understand the Bitwise Operators practically. This program allows the user to enter two integer variables, a and b, and we are going to use these two variables to show various operations.

import java.util.Scanner;

public class BitwiseOperators {
	private static Scanner sc;
	public static void main(String[] args) {
		int a, b;
		sc = new Scanner(System.in);
		System.out.println(" Please Enter two integer Value: ");
		a = sc.nextInt();
		b = sc.nextInt();
		
		System.out.format(" AND: %d & %d = %d \n", a, b, a & b);
		System.out.format(" OR : %d | %d = %d \n", a, b, a | b);
		System.out.format(" EXCLUSIVE OR: %d ^ %d = %d \n", a, b, a ^ b);
		System.out.format(" NOT : ~%d = %d \n", a, ~a);
		
		System.out.format(" LEFT SHIFT: %d << 1 = %d \n", a, a << 1);
		System.out.format(" RIGHT SHIFT: %d >> 1 = %d \n", b, b >> 1);
	}
}
Bitwise Operators in Java 1

In this example, the first three statements will ask the user to enter integer values, a and b. Next, we are going to assign the user input values to the variables.

The following System.out.format statements will perform on a and b, and then they will display the output.

In this Java Bitwise Operators example, we assigned the values as a = 12 and b = 25. The binary form of 12 = 00001100 and 25 = 00011001.

Let us see the Java calculations.

AND Operation = a & b
00001100 & 00011001 ==> 00001000 = 8

OR Operation = a || b
00001100 || 00011001 ==> 00011101 = 29

Next, Exclusive OR Operation = a ^ b
00001100 || 00011001 ==> 00010101 = 21

Complement Operation = ~a
As we said before, the complement of N will be -(N + 1). It means – (12 + 1) = -13

Left Shift = a << 1
00001100 << 1 = 00011000 = 24

Right Shift = b >> 1
00011001 >> 1 = 00001100 = 12