Java: Shift Operator

In the Java programming language, there are some shift operators which are used for manipulating the bits on data. So, let us dive into their types and check out what they do.

1. Left Shift Operator (<<)

The left shift operator shifts the left operand specified from right to left. It adds zeros. The number of zeros depends upon the right operand. So, 15 is 00001111 shifting left with 26 gives out 00001111, 00000000000000000000000000 which is in decimal value 1006632960.

public class Test
{
    public static void main(String[] args)
    {
        int val1 = 15, val2 = 26, val3, val4 = 10, val5;
        val5 = val1 << val2;
        System.out.println(val5);
    }
}

Output: 1006632960

2. Right Shift Operator (>>)

In the right shift, the operator removes the last bits of the first operand from the right side. So again, 15 is 00001111. Doing a right shift with, say 2, removes the last two bits 000011, which in decimal value is 3.

public class Test
{
    public static void main(String[] args)
    {
        int val1 = 15, val2 = 2, val3, val4 = 10, val5;
        val5 = val1 >> val2;
        System.out.println(val5);
    }
}

Output: 3

So likewise >>> and >> are both similar to what they do by pushing from left to right and removing the last right side bits by the specified operand.

Thu, 10/21/2021 - 12:28

Authored by

Ashwin is working with iVagus as a Technical Lead. He has experience in various technologies like Cypress, JavaScript, TypeScript, Rest Assured, Selenium, Cucumber, and Java.
Tags