Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Signed right-shift operator (>>)

The >> operator shifts bits right while replicating the sign bit. Learn operand promotion, distance masking, and how it differs from >>> and division.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

value >> distance

value >> distance shifts bits right, discarding low-order bits and replicating the sign bit on the left. In contrast, >>> inserts zeros.

Each operand independently undergoes unary numeric promotion; both must then have integral types. byte, short, and char become int. The result has the promoted left operand's type: int or long; a long right operand does not change this.

The distance is masked with & 31 for int or & 63 for long, even when negative. Thus, 8 >> 32 produces 8.

For effective distance s, the result equals division by 2 to the power s, rounded down. Thus, -9 >> 1 produces -5, whereas -9 / 2 produces -4: integer division rounds toward zero.

Examples

public class Main {
    public static void main(String[] args) {
        int value = -9;
        System.out.println(value >> 1);
        System.out.println(value / 2);
        System.out.println(value >>> 1);
        System.out.println(8 >> 32);
    }
}

Result

-5
-4
2147483643
8

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources