C Programs Tutorials | IT Developer
IT Developer

Java Programs



Share with a Friend

Operators & Expressions

Java Program: Demonstrate bitwise operators (&, |, ^, ~, <<, >>)

class BitwiseOperatorsDemo {

    public static void main(String[] args) {

 

        int a = 5;   // Binary: 0101

        int b = 3;   // Binary: 0011

 

        System.out.println("a = " + a);

        System.out.println("b = " + b);

 

        // Bitwise AND

        System.out.println("a & b = " + (a & b));

 

        // Bitwise OR

        System.out.println("a | b = " + (a | b));

 

        // Bitwise XOR

        System.out.println("a ^ b = " + (a ^ b));

 

        // Bitwise NOT

        System.out.println("~a = " + (~a));

 

        // Left Shift

        System.out.println("a << 1 = " + (a << 1));

 

        // Right Shift

        System.out.println("a >> 1 = " + (a >> 1));

    }

}

Output

OUTPUT :
a = 5
b = 3
a & b = 1
a | b = 7
a ^ b = 6
~a = -6
a << 1 = 10
a >> 1 = 2

Explanation

Binary Representation

a = 5  → 0101

b = 3  → 0011

  1. Bitwise AND (&)

a & b

0101

0011

----

0001  → 1

Result is 1
Bit is 1 only if both bits are 1

  1. Bitwise OR (|)

a | b

0101

0011

----

0111  → 7

Result is 7
Bit is 1 if any one bit is 1

  1. Bitwise XOR (^)

a ^ b

0101

0011

----

0110  → 6

Result is 6
Bit is 1 if bits are different

  1. Bitwise NOT (~)

~a

a  =  00000000 00000000 00000000 00000101

~a =  11111111 11111111 11111111 11111010

Result is -6
Formula: ~n = -(n + 1)

  1. Left Shift (<<)

a << 1

0101 << 1 → 1010  → 10

Multiplies the number by 2

  1. Right Shift (>>)

a >> 1

0101 >> 1 → 0010 → 2

Divides the number by 2

Summary Table

Operator

Name

Description

&

AND

Both bits must be 1

`

`

OR

^

XOR

Bits must be different

~

NOT

Inverts all bits

<< 

Left Shift

Multiplies by 2

>> 

Right Shift

Divides by 2

Key Learning Points

Bitwise operators work on binary data
Used in low-level programming, encryption, graphics, and performance optimization
~ gives negative result due to 2’s complement representation