Java - What is the result of 13 << 35?

Question

int i = 13;
i  = i << 35;
System.out.println(i);

What is output?



Click to view the answer

104

Note

int occupies 32 bits.

32 bits are used to represent 13.

You can shift all bits to the left only by 31 bits in an int.

If the left-hand operand of << is int, only five lower order bits' value of the right-hand operand is used as the number of bits to shift.

For example, in 13 << 35, the right-hand operand (35) can be represented in binary as follows:

00000000000000000000000000100011

The five lower order bits in 35 are 00011, which is equal to 3.

When you write 13 << 35, it is equivalent to writing 13 << 3.

13 << 35 can be considered as 13 << (35 % 32) which is 13 << 3.

Demo

public class Main {
  public static void main(String[] args) {
    int i = 13;/*from   w  w w. j ava  2s. c o  m*/
    i  = i << 35;
    System.out.println(i);
    
    i = 13;
    i  = i << 3;
    System.out.println(i);
  }
}

Result

Left shift long

If the left-hand operand is long, the value of the first six lower order bits of the right-hand operand is used as the number of bits to shift.

The six lower order bits of 35 are 100011.

long  i = 13;
i = i << 65;

is

i = i << (65%64);

Demo

public class Main {
  public static void main(String[] args) {
    long  i = 13;
    i = i << 65;//from w w  w.j av a  2  s.  c  o  m
    System.out.println(i);
    
    i = 13;
    i  = i << 1; 
    System.out.println(i);
  }
}

Result