Mega Code Archive

 
Categories / Java Book / 001 Language Basics
 

0032 Left Shift

It has this general form: value << num The following code shifts byte type variable. public class Main { public static void main(String args[]) { byte a = 64, b; int i; 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: Original value of a: 64 i and b: 256 0 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; for (int i = 0; i < 4; i++) { num = num << 1; System.out.println(num); } } } The program generates the following output: 536870910 1073741820 2147483640 -16