The Left Shift

The left shift operator, <<, shifts all of the bits in a value to the left a specified number of times.

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
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.