int a = 3; a <<= 1; System.out.println(a);So shifting to the left by 1 is like multiplying by 2 to the power of 1, which is like multiplying the variable by 2. Hence the result:
6
Binary Left Shift Assign by 2 is like multiplying the variable by 2 to the power of 2, which is like multiplying by 4.
int a = 3; a <<= 2; System.out.println(a);Which of course, 3 multiplied by 4 results to:
12Continuing, left shifting by 3 is like multiplying by 2 to the power of 3 which is 8.
int a = 3; a <<= 3; System.out.println(a);So the result is 3 times 8:
24
If we don't know how much to left shift a variable, we can use another variable to hold the value, for example:
int a = 21; int b = 4; a <<= b; System.out.println(a);So we are left shifting a by the value of b, which is shifting the value of 21 by 4. This is equivalent to 21 multiplied by 2 to the power of 4, which is 21 times 16. Which gives us:
336
int a = 6; int b = 3; a <<= b + 2; System.out.println(a);So we evaluate first b + 2, which results to 5. So we are multiplying 6 by 2 to the power of 5, which is 6 times 32, that gives us the output below:
192