Bitwise operator | Java

Bitwise operator | Java

Basics • Java Fundamentals

In Java, bitwise operators are used to perform operations on individual bits of integer types (int, long, short, char, and byte).

We can apply this operator for integral type also in boolean as well.

There are several bitwise operators, each of which operates on corresponding bits of two integer values.

Here are the bitwise operators in Java:

  1. Bitwise AND (&):

    • Performs a bitwise AND operation between each pair of corresponding bits.
    int a = 5;      // binary: 0101
    int b = 3;      // binary: 0011
    int result = a & b; // binary: 0001 (1 in decimal)
  1. Bitwise OR (|):

    • Performs a bitwise OR operation between each pair of corresponding bits.
    int x = 5;      // binary: 0101
    int y = 3;      // binary: 0011
    int result = x | y; // binary: 0111 (7 in decimal)
  1. Bitwise XOR (^):

    • Performs a bitwise exclusive OR operation between each pair of corresponding bits. The result is 1 if the bits are different.
    int p = 5;      // binary: 0101
    int q = 3;      // binary: 0011
    int result = p ^ q; // binary: 0110 (6 in decimal)
  1. Bitwise NOT (~):

    • Inverts the bits of a single operand.

    • This operator is only applicable for integral not for boolean.

    System.out.println(~5); // -6
    System.out.println(~-6); // 5
  1. Left Shift (<<):

    • Shifts the bits of the left operand to the left by a specified number of positions.
    int value = 5;    // binary: 0000 0000 0000 0000 0000 0000 0000 0101
    int result = value << 2; // binary: 0000 0000 0000 0000 0000 0000 0001 0100 (20 in decimal)
  1. Right Shift (>>):

    • Shifts the bits of the left operand to the right by a specified number of positions. The sign bit is used to fill the vacant positions (for signed integers).
    int number = -16; // binary: 1111 1111 1111 1111 1111 1111 1111 0000
    int result = number >> 2; // binary: 1111 1111 1111 1111 1111 1111 1111 1100 (-4 in decimal)
  1. Unsigned Right Shift (>>>):

    • Similar to right shift (>>), but the vacant positions are filled with zeros.
    int num = -16;    // binary: 1111 1111 1111 1111 1111 1111 1111 0000
    int result = num >>> 2; // binary: 0011 1111 1111 1111 1111 1111 1111 1100 (1073741820 in decimal)
  1. Boolean compliment operator (!)

    • We can apply this operator only for Boolean type.

    • If you apply this operator on any other type then will get compiled time error.

    System.out.println(!4); // ! cannot be applied to int
    System.out.println(!true); // false
Bitwise OperatorApplicable for
&, `, ^`
~For integral type only
!For Boolean type only

Bitwise operators are often used in low-level programming, graphics programming, and situations where manipulating individual bits is necessary for efficient operations.

Did you find this article valuable?

Support Xander Billa by becoming a sponsor. Any amount is appreciated!