0

Please look at this code:

    int a = 5, b = 7;
    System.out.println(++a + b-- - a-- * --b);

It outputs -17. But I dont understand why. In my opinion output should be -19. Because first of all we do multiplication 5*6 = 30, then 5 + 6 = 11, finally 11-30 = -19. Could someone tell me why output is -17?

2 Answers2

4

Here is an explanation, using the order of operations in Java:

int a = 5, b = 7;

++a + b-- -  a-- * --b
  6 + 7   - (6 * 5)
  13 - 30
  -17

The first term is evaluated as 6, because ++a means to increment a first then evaluate. On the other hand, b-- evaluates as 7, because the postfix -- occurs after b. For the two terms involved in the multiplication, we place them in parentheses, due to the order of operations rules in Java. The same logic applies there, and we get 30 for the product.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
0

You are confusing evaluation order with precedence.

The operands ++a, b--, a--, and --b are evaluated left-to-right, regardless of operator precedence.

Andreas
  • 154,647
  • 11
  • 152
  • 247