Skip to main content

Operators

Shift Operators

In Java, shift operators are used to shift the bits of a binary number to the left or right. There are three types of shift operators:

  1. Left shift (<<)
  2. Signed right shift (>>)
  3. Unsigned right shift (>>>).

Left Shift (<<):

This operator shifts the bits of a number to the left by a specified number of positions.

The leftmost bits are filled with zeros.

public class ShiftOperators {
  public static void main(String[] args) {
    int num = 5; // binary: 0000 0101
    int result = num << 2; // result: 0001 0100 (20 in decimal)
    System.out.println(result);
  }
}

Signed Right Shift (>>):

This operator shifts the bits of a number to the right by a specified number of positions.

The rightmost bits are filled with the sign bit (the leftmost bit, which determines the sign of the number).

public class ShiftOperators {
  public static void main(String[] args) {
    int num = -8; // binary: 1111 1000 (negative number)
    int result = num >> 2; // result: 1111 1110 (-2 in decimal)

    System.out.println(result);
  }
}

Unsigned Right Shift (>>>):

This operator shifts the bits of a number to the right by a specified number of positions.

The rightmost bits are filled with zeros, regardless of the sign of the number.

public class ShiftOperators {
  public static void main(String[] args) {
    int num = 10; // binary: 0000 1010
    int result = num >>> 2; // result: 0000 0010 (2 in decimal)

    System.out.println(result);
  }
}

Shift operators are often used in low-level programming, such as manipulating binary data or optimizing performance-sensitive code. They can also be useful for implementing bitwise operations, encoding/decoding data, or handling bit-level flags in data structures.