-2

Hello everyone I have a very simple question that I just don't understand. I've tried googling it but haven't found a clear answer.

What is x after the following statements?

int x = 2;
int y = 1;
x *= y + 1;

I know that the answer is 4 but I don't understand why it is 4. Just need some clarity on what x* means exactly. Thanks!

Ole V.V.
  • 76,217
  • 14
  • 120
  • 142
Student
  • 1
  • 1
  • `x = x * y + 1`. `x = 2 * 1 + 1`. `x = 2 * 2`. `x = 4` – Elliott Frisch Nov 30 '18 at 23:36
  • If you know what `x += y` means, then `x -= y`, `x *= y`, `x /= y`, and `x %= y` should all be intuitive. See [Compound assignment operators in Java](https://www.geeksforgeeks.org/compound-assignment-operators-java/) – Andreas Dec 01 '18 at 00:32

3 Answers3

2

I think this line is the one why you ask

x *= y + 1;

This is a shorthand for

x = x * (y + 1);

This works also with other operators like - and +, when the first variable is the same as the variable on the left side (which will be assigned).

Donat
  • 3,239
  • 2
  • 10
  • 21
0

The x*= symbol means x=x* the result of whatever you put after the equals symbol.

x*= y+1 will turn to x = x * (y+1). The expresion you put after equals is evaluated first and then multiplied with x. The result will be cast to the type of the assignment variable (x).

0

Of course x is 4, if you don't understand the last statement, you can read it like this

x = x * y + 2
chinloyal
  • 911
  • 11
  • 39