Sep 03, 2019 Core Java, Examples comments

The Binary left Shift Operator is an efficient way of multiplying a number by a power of two. And when we do that operation, we also typically want to assign back the resulting product to the original variable. This is where the Binary Left Shift Assign Operator becomes handy. Below are some examples on how to use Binary Left Shift Assign Operator in Java.

### Binary Left Shift Assign With Literal

The Binary Left Shift is denoted by the symbol

**<<**, and if we want the Binary Left Shift Assign , we just add the equal sign which gives us this symbol for the operator

**<<=** . Using this will left shit the value of the variable by the value of the expression at the right. And then assign it back to the variable. Below is a simple example on Binary Left Shift Assign with Literal in Java, using the value 1:

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:

12

Continuing, 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

### Binary Left Shift Assign With Another variable

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

### Binary Left Shift Assign With An Expression

The right side of the Binary Left Shift Assign can be any expression, for example:

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