Bitwise & Shift Operators in Java

A shift operator performs bit manipulation on data by shifting the bits of its first operand right or left. The bitwise operators are the operators used to perform the operations on the data at the bit-level. When we perform the bitwise operations, then it is also known as bit-level programming. It consists of two digits, either 0 or 1.

OperatorDescriptionExampleExplanation
&Bitwise AND5 & 3Performs AND operation on each bit (1 if both bits are 1)
|Bitwise OR5 | 3Performs OR operation on each bit (1 if any bit is 1)
^Bitwise XOR (exclusive OR)5 ^ 3Performs XOR on each bit (1 if bits differ)
~Bitwise NOT (One's complement)~5Inverts each bit (0 → 1 and 1 → 0)
<<Left Shift5 << 1Shifts bits left, fills right with 0 (multiplies by 2n)
>>Signed Right Shift5 >> 1Shifts bits right, fills left with sign bit (preserves sign)
>>>Unsigned Right Shift-5 >>> 1Shifts bits right, fills left with 0 (does not preserve sign)
Media content

Code Snippet

//Bitwise & Shift Operators in Java

public class App {
    public static void main(String[] args) {
        // Bitwise Operators
        int a = 5; // binary: 0101
        int b = 3; // binary: 0011

        System.out.println("Bitwise AND (5 & 3): " + (a & b)); // 1 (0001)
        System.out.println("Bitwise OR (5 | 3): " + (a | b)); // 7 (0111)
        System.out.println("Bitwise XOR (5 ^ 3): " + (a ^ b)); // 6 (0110)
        System.out.println("Bitwise NOT (~5): " + (~a)); // -6 (two's complement)

        // Shift Operators
        int c = 5; // 0000 0101

        System.out.println("Left shift (5 << 1): " + (c << 1)); // 10 (0000 1010)
        System.out.println("Signed right shift (5 >> 1): " + (c >> 1)); // 2 (0000 0010)

        int d = -10; // negative number example
        System.out.println("Signed right shift (-10 >> 1): " + (d >> 1)); // -5 (fills with sign bit)
        System.out.println("Unsigned right shift (-10 >>> 1): " + (d >>> 1)); // Large positive number (fills with 0)
    }
}