1

Java says that the result of the following calculation is -24. But isn't --(-3)*(6)++ == -4*7 == -28?

public int rechnung3() { int k = -3; int i = 6; return --k*i++; } 

2 Answers 2

1

No because the postfix increment happens after the expression has been evaluated. So essentially, the i is only incremented after the result has been stored on the stack.

So what happens is equivalent to something like this:

int k = -3; int i = 6; k = k -1; // --k makes k = -4 int tmp = k * i; // a temporary location stores the value of (--k) * i = -24 i = i + 1; // i++ increments i, now i = 7 return tmp; // returns -24 (the result from the auxiliary location) 
Sign up to request clarification or add additional context in comments.

2 Comments

Was writing my own answer but yours is more succinct. Just to add that the values of k and i will be -4 and 7 after but -4 and 6 during the calculation.
@KevinPluck - yeah, I've updated the answer with some more details
1

Your variable k has the "pre-decrement" operator, meaning that the value is reduced before it is used in the calculation. So your -4 is correct. However, the variable i has the "post-increment" operator, meaning that the value is increased after it is used in the calculation. So, the value that is used is 6. If there were any code later in the function (if you did not return immediately), the value would be 7 if you used the variable again.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.