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 Java 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 meaning. For example, Consider x = 6 and y = 8 and their values in binary form are

x = 0110

y = 1000

Operators MeaningExamples
&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 Java 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.

package JavaOperators;

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(" Bitwise AND Operator: %d & %d = %d \n", a, b, a & b);
		System.out.format(" Bitwise OR Operator: %d | %d = %d \n", a, b, a | b);
		System.out.format(" Bitwise EXCLUSIVE OR: Operator %d ^ %d = %d \n", a, b, a ^ b);
		System.out.format(" Bitwise NOT Operator: ~%d = %d \n", a, ~a);
		
		System.out.format(" LEFT SHIFT Operator: %d << 1 = %d \n", a, a << 1);
		System.out.format(" RIGHT SHIFT Operator: %d >> 1 = %d \n", b, b >> 1);
	}
}
Bitwise Operators in Java 1

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

The following System.out.format statements will perform the bitwise operations 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.

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

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

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

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

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

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