Java Left Shift Operator
In this chapter you will learn:
- What is Left Shift Operator
- Syntax for Left Shift Operator
- Example - Left Shift Operator
- Example - double the original value
Description
The left shift operator, <<, shifts all of the bits in a value to the left a specified number of times.
Syntax
It has this general form:
value << num
Example
The following code shifts byte type variable.
public class Main {
public static void main(String args[]) {
byte a = 64, b;
int i;// w w w .j a v a 2 s .c o m
i = a << 2;
b = (byte) (a << 2);
System.out.println("Original value of a: " + a);
System.out.println("i and b: " + i + " " + b);
}
}
The output generated by this program is shown here:
Example 2
Each left shift has the effect of doubling the original value. The following program illustrates this point:
public class Main {
public static void main(String args[]) {
int num = 0xFFFFFFF;
/*from w ww . ja v a 2 s.c om*/
for (int i = 0; i < 4; i++) {
num = num << 1;
System.out.println(num);
}
}
}
The program generates the following output:
Next chapter...
What you will learn in the next chapter:
- How to shift bits in a value to the right
- Syntax for Right Shift Operator
- Example - Right Shift Operator