Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Left-shift operator (<<)

The << operator shifts an integer's bits left, filling the right side with zeros. The promoted left operand determines the result width and how the shift distance is masked.

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

Syntax

value << distance

value << distance moves bits left, filling the right side with zeros and discarding bits beyond the result width. This corresponds to multiplication by a power of two using the effective distance, with possible overflow.

Each operand separately undergoes unary numeric promotion: byte, short, and char become int. After promotion, both operands must have integral types; boolean, float, and double are invalid. Only the left operand determines the result type: int or long. A long right operand does not widen the result.

The distance is masked: with & 31 for int, or & 63 for long. Thus, 1 << 32 produces 1, while 1L << 32 produces 4294967296. Negative distances are also masked rather than rejected.

Overflow throws no exception and can change the sign: 1 << 31 produces -2147483648. Use 1L when you need a 64-bit mask; subsequently assigning an int result to long cannot recover discarded bits.

Examples

public class LeftShiftDemo {
    public static void main(String[] args) {
        byte value = 3;
        System.out.println(value << 2);
        System.out.println(1 << 32);
        System.out.println(1L << 32);
        System.out.println(1 << 31);
    }
}

Result

12
1
4294967296
-2147483648

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