Shift Operators

Rumman Ansari   Software Engineer   2025-08-24 03:58:53   146  Share
Subject Syllabus DetailsSubject Details
☰ TContent
☰Fullscreen

Table of Content:

What are Shift Operators?

Shift operators in Java are used to move the bits of a number to the left or right. Shifting changes the value of the number because bits are moved, and zeros (or the sign bit) are filled in depending on the type of shift.

Java has 3 shift operators:

Operator Name Description
<< Left shift Shifts bits to the left, fills with 0 from the right
>> Right shift (signed) Shifts bits to the right, fills with the sign bit (0 for positive, 1 for negative)
>>> Right shift (unsigned) Shifts bits to the right, fills with 0 always

Left Shift (<<)

  • Syntax: number << n

  • Moves bits n positions to the left

  • Fills 0 from the right

  • Equivalent to multiplying the number by 2^n (for positive numbers)

Example:


int x = 5;        // Binary: 0000 0101
int y = x << 2;   // Shift left by 2 bits: 0001 0100
System.out.println(y); // Output: 20

Explanation: 5 * 2^2 = 20


3. Right Shift (>>)

  • Syntax: number >> n

  • Moves bits n positions to the right

  • Fills the leftmost bits with the sign bit

    • Keeps positive numbers positive

    • Keeps negative numbers negative

  • Equivalent to dividing by 2^n (integer division)

Example:


int x = 20;       // Binary: 0001 0100
int y = x >> 2;   // Shift right by 2 bits: 0000 0101
System.out.println(y); // Output: 5

Negative number example:


int x = -20;      // Binary: 1110 1100 (Two's complement)
int y = x >> 2;   // Shift right by 2 bits: 1111 1011
System.out.println(y); // Output: -5


Unsigned Right Shift (>>>)

  • Syntax: number >>> n

  • Moves bits n positions to the right

  • Always fills with 0 on the left

  • Only makes a difference for negative numbers

Example:


int x = -20;      // Binary: 1111 1111 1111 1111 1111 1111 1110 1100
int y = x >>> 2;  
System.out.println(y); // Output: 1073741819

Notice: The result is now positive because zeros were filled from the left.


Quick Summary Table

Operator Fill Bits Effect
<< 0 (right) Multiply by 2^n
>> Sign bit Divide by 2^n (signed)
>>> 0 (left) Divide by 2^n (unsigned, negative becomes positive)



Stay Ahead of the Curve! Check out these trending topics and sharpen your skills.