Operators
Java Program to Demonstrate Bitwise Operators
A Java program to demonstrate the usage of bitwise operators.
Problem Description
Write a Java program to demonstrate the usage of bitwise operators: AND (&), OR (|), XOR (^), Complement (~), Left Shift (<<), Right Shift (>>), and Unsigned Right Shift (>>>).
Code
public class BitwiseOperators {
public static void main(String[] args) {
int a = 5; // 0101 in binary
int b = 3; // 0011 in binary
System.out.println("a & b: " + (a & b)); // 0001 = 1
System.out.println("a | b: " + (a | b)); // 0111 = 7
System.out.println("a ^ b: " + (a ^ b)); // 0110 = 6
System.out.println("~a: " + (~a)); // 1010 = -6 (in 2's complement)
System.out.println("a << 1: " + (a << 1)); // 1010 = 10
System.out.println("a >> 1: " + (a >> 1)); // 0010 = 2
System.out.println("a >>> 1: " + (a >>> 1)); // 0010 = 2
}
}Output
a & b: 1
a | b: 7
a ^ b: 6
~a: -6
a << 1: 10
a >> 1: 2
a >>> 1: 2Explanation
&(Bitwise AND): Performs AND on each bit.|(Bitwise OR): Performs OR on each bit.^(Bitwise XOR): Performs XOR on each bit.~(Bitwise Complement): Inverts all bits.<<(Left Shift): Shifts bits to the left, filling with 0.>>(Right Shift): Shifts bits to the right, preserving sign.>>>(Unsigned Right Shift): Shifts bits to the right, filling with 0.
Try Yourself
- Odd or Even: Use
&to check if a number is odd or even. (Hint:n & 1). - Swap with XOR: Swap two numbers using only
^and no temporary variable. - Negative Shift: Try shifting a negative number (e.g.,
-5) using>>and>>>. What is the difference? - Power of 2: Multiply a number by 2 using
<<. Divide by 2 using>>. - Brain Twister: How can you check if a number is a power of 2 using bitwise operators?
Hint:
(n & (n - 1)) == 0
