Java From Beginner To Advanced

0% completed

Previous
Next
Shift Operators

Shift operators in Java move the bits of an integer value to the left or right. They are used for various low-level programming tasks, such as bit manipulation and efficient multiplication or division by powers of two.

Shift Operators

OperatorDescriptionExample
<<Left shift: Shifts bits to the left, filling in zeros from the right.a << n shifts a left by n positions.
>>Right shift: Shifts bits to the right, preserving the sign (sign extension).a >> n shifts a right by n positions.
>>>Unsigned right shift: Shifts bits to the right, filling in zeros from the left (no sign extension).a >>> n shifts a right by n positions.

Example 1: Using Left Shift (<<) and Right Shift (>>) Operators

Below is an example demonstrating the left and right shift operations.

Java
Java

. . . .

Explanation:

  • Left Shift (<<):
    • Shifts the bits of a (which is 8) 2 positions to the left, effectively multiplying it by 2² (4).
    • The result is 32.
  • Right Shift (>>):
    • Shifts the bits of a 2 positions to the right, effectively dividing it by 2² (4).
    • The result is 2.

Example 2: Using Unsigned Right Shift (>>>) Operator

Below is an example that demonstrates the unsigned right shift operator on a negative number.

Java
Java

. . . .

Explanation:

  • Unsigned Right Shift (>>>):
    • For a negative number, a = -16, the unsigned right shift operator shifts the bits to the right by 2 positions, filling the leftmost bits with zeros rather than extending the sign bit.
    • This results in a large positive number because the sign bit is not preserved.

These examples illustrate how shift operators move bits in an integer. Experiment with these operators to see how shifting affects values and aids in performing efficient arithmetic operations.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next