Java Left Shift Operator

In this chapter you will learn:

  1. What is Left Shift Operator
  2. Syntax for Left Shift Operator
  3. Example - Left Shift Operator
  4. 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:

  1. How to shift bits in a value to the right
  2. Syntax for Right Shift Operator
  3. Example - Right Shift Operator
Home »
  Java Tutorial »
    Java Langauge »
      Java Operator
Java Arithmetic Operators
Java Compound Assignment Operators
Java Increment and Decrement Operator
Java Logical Operators
Java Logical Operators Shortcut
Java Relational Operators
Java Bitwise Operators
Java Left Shift Operator
Java Right Shift Operator
Java Unsigned Right Shift
Java ternary operator