-6
int a = 10;
System.out.println(a-- * a--);

what will be the output of these print statement and why??

in post decrement we actually observe that

  • the value is used before getting change

but here I am getting in one of the operator (a--) is 10 and in another operator (a--) with which we are multiplying is getting 9.

overall the output which I came across is 100 but the actual output is 90

please explain how?

Zabuzard
  • 25,064
  • 8
  • 58
  • 82
  • "the value is used before getting change" exactly - the value still changes. Why did you expect the value to stay at 10, when the second `a--` is run? – Sweeper Apr 22 '23 at 12:39
  • 2
    The real-world output is "your pull request is rejected; reformulate that expression for clarity". – Arfur Narf Apr 22 '23 at 12:46
  • The operands used in a multiplication are evaluated left to right. Evaluating the left `a--` yields 10 as you expected and decrements `a` to 9. Now I leave to you what happens when the right operands is evaluated. :-) – Ole V.V. Apr 22 '23 at 13:08

1 Answers1

-1

Java sees A * B, so it first needs to compute both arguments, A and B.

The left operand (A) a-- is executed, making a = 9, but returning the value it had before, so 10.

We now have 10 * a--. Next, Java executes the right operand (B) and we get a = 8, but we use the value it had before the decrement, so 9.

We get 10 * 9, which is 90. And a = 8.

Zabuzard
  • 25,064
  • 8
  • 58
  • 82
  • "_but **returning** the value it had before_" - Should that read "_but **using** the value it had before_"? As in the value _used_ in the multiplication is `10`. – andrewJames Apr 22 '23 at 14:31
  • Never mind. It's returned so it can be used. – andrewJames Apr 22 '23 at 14:37
  • Essentially, the expression `a--` (with a = 10), has the side-effect of making `a = 9` and then evaluating to `10`. While `--a` has the same side-effect, but evaluates to `9`. – Zabuzard Apr 22 '23 at 14:50