JAVA Syllabus
QUESTIONS & ANSWERS

What is the difference between >> and >>>?

In many programming languages, including Java and JavaScript, the ">>" and ">>>" operators are used for bitwise right shift operations. The difference between the two operators lies in how they handle the sign bit of the shifted value.

The ">>" operator performs a signed right shift, which means that it preserves the sign of the value being shifted. If the value being shifted is negative (i.e., has a sign bit of 1), the ">>" operator will shift in 1's on the left-hand side to preserve the negative sign. If the value being shifted is positive (i.e., has a sign bit of 0), the ">>" operator will shift in 0's on the left-hand side.

The ">>>" operator, on the other hand, performs an unsigned right shift, which means that it always shifts in 0's on the left-hand side, regardless of the sign of the value being shifted. This operator is often used for bit manipulation and is useful when you want to ignore the sign bit and treat the shifted value as a non-negative number.

Here's an example to illustrate the difference:

int x = -8; // binary: 11111111111111111111111111111000
System.out.println(x >> 2); // output: -2 (binary: 11111111111111111111111111111110)
System.out.println(x >>> 2); // output: 1073741822 (binary: 00111111111111111111111111111110)

In this example, we're shifting the value -8 two bits to the right. With the ">>" operator, the sign bit is preserved, so the result is still negative (-2). With the ">>>" operator, the sign bit is ignored, so the result is a large positive number (1073741822).

03/03/2023, 12:54 pm Read : 160 times