Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Left-shift assignment operator (<<=)

The <<= operator shifts bits left and stores the result in the same variable. If the variable has a primitive type, the result is implicitly converted back to that type.

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

Syntax

variable <<= distance;

variable <<= distance combines << with assignment. When the compound assignment is valid, it corresponds to variable = (T) (variable << distance), where T is the variable's type, except that the left-hand side is evaluated only once.

For the shift, the operands are unboxed if necessary and must have integral types. Unary numeric promotion converts byte, short, and char to int; long remains long. With a primitive byte left operand, the int result is implicitly narrowed to byte, so no explicit cast is needed. In contrast, Byte b = 64; b <<= 1; does not compile: the compound assignment cannot implicitly narrow the int shift result to byte and then box it as Byte.

Zeros enter on the right; bits shifted out on the left are discarded without an overflow exception. Only the lowest 5 bits of the distance are used for int or 6 for long, including negative distances. Thus, shifting an int by 32 leaves it unchanged.

The example demonstrates an ordinary shift, narrowing to byte, and distance masking.

Examples

public class Main {
    public static void main(String[] args) {
        int value = 3;
        value <<= 2;
        byte small = 64;
        small <<= 1;
        int masked = 3;
        masked <<= 32;
        System.out.println(value);
        System.out.println(small);
        System.out.println(masked);
    }
}

Result

12
-128
3

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