Search code examples
javaassignment-operator

What does <<= or >>= mean in Java?


I was learning about assignment operators in Java in W3schools. But I didn't get what these two operators mean?


Solution

  • These are examples of assignment operators. Essentially, they both perform the arithmetic operation on a variable, and assign its result to that variable, in a single operation. They're equivalent to doing it in two steps, for the most part:

    int a = 23;
    int b = 2;
    
    a += b; // addition - same as `a = a + b`
    a -= b; // subtraction
    a *= b; // multiplication
    a /= b; // floor division
    a %= b; // modulo division
    a &= b; // bitwise and
    a |= b; // bitwise or
    a ^= b; // bitwise xor
    a >>= b; // right bitshift
    a <<= b; // left bitshift
    

    The bitshift operations in particular are the ones you're asking about. They take the binary representation of a number, and shift it left or right by the given number of places, filling in missing spaces with zeroes. For example, the binary representation of 23 is 00010111.

    So, 23 << 2 would be equal to 01011100, or 92; whereas 23 >> 2 would be equal to 00000101, or 5.

    You could also think of it as doing integer multiplication or division using powers of two:

    • a << b will generally produce the same result as a * Math.pow(2, b)
    • a >> b will generally produce the same result as a / Math.pow(2, b)