Slide 1
Slide 2
Slide 3

Bitwise Operators in java programming (V19)

No Comments

Bitwise Operators

Bitwise operators in Java perform operations at the bit level. They work with integer values (byte, short, int, long) and operate on each bit individually.

List of Bitwise Operators

Operator Name Description
& Bitwise AND Performs a bit-by-bit comparison between two operands and returns 1 only if both corresponding bits are 1, otherwise returns 0.
| Bitwise OR Performs a bit-by-bit comparison between two operands and returns 0 only if both corresponding bits are 0, otherwise returns 1.
^ Bitwise XOR (Exclusive OR) Performs a bit-by-bit comparison between two operands and returns 0 only if both bits are 0 or both are 1, otherwise returns 1.
~ Bitwise Complement Bitwise complement (~) flips all bits of a number. It converts 0s to 1s and 1s to 0s.
<< Left Shift Shifts all bits of the operand to the left. The bits are shifted left by the number of positions specified.
>> Right Shift Shifts all bits of the operand to the right by the number of positions specified.
>>> Unsigned Right Shift Shifts all bits to the right while filling the left-side bits with 0, regardless of the sign.

Note: Understanding Bitwise Complement Calculation

For a number N, the bitwise complement is computed as:

        N = −(N + 1)

This is because the computer stores negative numbers in two’s complement form.

Example: ~5

  • Binary of 5 (8-bit representation): 00000101

  • Bitwise Complement (~): 11111010

Convert to Decimal (Two’s Complement):

  1. Invert bits: 00000101

  2. Add 1: 00000110 (which is 6 in decimal)

  3. Apply negative sign: ~5 = -6

Source Code:

Copied!
public class BitwiseOperators {
    public static void main(String[] args) {
        int a = 5, b = 3; // a = 0101, b = 0011
        
        System.out.println("a & b: " + (a & b));  // 0101 & 0011 = 0001 (1)
        System.out.println("a | b: " + (a | b));  // 0101 | 0011 = 0111 (7)
        System.out.println("a ^ b: " + (a ^ b));  // 0101 ^ 0011 = 0110 (6)
        System.out.println("~a: " + (~a));        // ~0101 = 1010 (-6 in 2's complement)
        System.out.println("a << 1: " + (a << 1)); // 0101 << 1 = 1010 (10)
        System.out.println("a >> 1: " + (a >> 1)); // 0101 >> 1 = 0010 (2)
        System.out.println("a >>> 1: " + (a >>> 1)); // 0101 >>> 1 = 0010 (2)
    }
}

Result:

Watch the video:


Ebook: https://softkhpc.blogspot.com/2025/05/java-programming-ebooks.html

back to top