-5

Output is 20 but i am not getting the logic behind this.Please anyone explain

    public static void main(String[] args)
    {
    System.out.println(5<<2);   
    }
Monika
  • 3
  • 1
  • 3
    `x << y` is equal to `x * (2 ^ y)`. So `5 << 2` is equal to `5 * (2 ^ 2)` => 20. You should read a tutorial on bit shifting operators to understand the logics behind this. – Ronan Boiteau Jul 28 '18 at 11:24
  • Each left shift is like multiplying by 2 if you don't get an overflow. So to left shift by 2 is like *2*2 or *4 – Peter Lawrey Jul 28 '18 at 13:29

1 Answers1

1

If you read about Bitwise and Bit Shift Operators:-

The unary bitwise complement operator "~" inverts a bit pattern; it can be applied to any of the integral types, making every "0" a "1" and every "1" a "0". For example, a byte contains 8 bits; applying this operator to a value whose bit pattern is "00000000" would change its pattern to "11111111".

The signed left shift operator "<<" shifts a bit pattern to the left, and the signed right shift operator ">>" shifts a bit pattern to the right. The bit pattern is given by the left-hand operand, and the number of positions to shift by the right-hand operand. The unsigned right shift operator ">>>" shifts a zero into the leftmost position, while the leftmost position after ">>" depends on sign extension.

The bitwise & operator performs a bitwise AND operation.

The bitwise ^ operator performs a bitwise exclusive OR operation.

The bitwise | operator performs a bitwise inclusive OR operation.

The following program, BitDemo, uses the bitwise AND operator to print the number "2" to standard output.

class BitDemo {
    public static void main(String[] args) {
        int bitmask = 0x000F;
        int val = 0x2222;
        // prints "2"
        System.out.println(val & bitmask);
    }
}
Ravindra Kumar
  • 1,842
  • 14
  • 23