JamesQ - 4 months ago 25

Java Question

`int t = 3;`

t = 1 << t;

System.out.println(t);

int n = 3;

n <<= 1;

System.out.println(n);

This is the code I wrote in Java 1.8. The result is 8 and 6. Shouldn't be the result is both 6?

Answer

The first operator `x << y`

shifts the binary representation of `x`

by `y`

bits to the left and returns this result.
The second operator `x <<= y`

shifts the binary representation of `x`

by `y`

bits to the left and stores the result in `x`

.

Applied to your example, `1 << 3`

would be `0x0001 << 3 = 0x1000 = 8`

.
The second one, `3 << 1`

, would be `0x011 << 1 = 0x110 = 6`

.