2

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

CypherZ
  • 77
  • 8
  • 1
    Those are short notation of left and right shift. Kinda like `+=`. It is explained on their website though. These are bit wise operations. https://stackoverflow.com/questions/55203804/understanding-the-right-shift-operator-with-bit-shifting – Yoshikage Kira Jun 01 '21 at 02:52
  • 2
    These are [Compound assignment operators](https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.26.2), related to [Shift operators](https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.19) – Dawood ibn Kareem Jun 01 '21 at 02:56
  • [Compound assignment operators in Java](https://www.geeksforgeeks.org/compound-assignment-operators-java/) – Ole V.V. Jun 01 '21 at 04:01

2 Answers2

2

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)
Green Cloak Guy
  • 23,793
  • 4
  • 33
  • 53
1

it's short expression, just like i = i >> 2 and i = i << 2

MoYang
  • 11
  • 2
  • 1
    I doubt they understand what that means. It would be better if you expand your answer so it is better. Like what does shifting left or right does. – Yoshikage Kira Jun 01 '21 at 02:54
  • my bad, I'm a new comer,I would rewrite my answer – MoYang Jun 01 '21 at 02:55
  • Sure, you can [edit] your answer as many times as you want. People tend to vote on good detailed answer. – Yoshikage Kira Jun 01 '21 at 02:56
  • 1
    And it's not entirely true - with a compound assignment operator, the left hand side is only evaluated once. This can be an important distinction. Also, the type conversion rules are a bit different. – Dawood ibn Kareem Jun 01 '21 at 02:57