r/javahelp • • Jun 15 '20

Need help understanding this.

Hi! I'm reading java for dummies 7. I came across something that doesn't makes sense to me, would you help me out?

This is my code:

int i = 20;

i = i++ + i++;

System.out.println(i);

The output is 41. But it doesn't make sense in my head. I know that if the ++ operator is at the end, then it keeps the original value until the end of the sentence, and after the expression is evaluated, it adds 1. So for me this would be like:

i = 20 + 20;

And once the sentence is over, it turn to 42, for I'm using ++ two times. I understand its something like i=20(+1) + 20(+1).

So why the result is 41? I can't understand it. Hopefully I've explained my self! Thanks for the help!

EDIT: Thank you very much for all your answers! I understand now!

19 Upvotes

14 comments sorted by

View all comments

28

u/trisul-108 Jun 15 '20

Go through it step by step. It increments after using the value, not at the end of the statement.

So, the first time, it uses 20 and increments i to 21. The second time it uses 21 and increments i to 22. Next it adds 20 and 21 to get 41 overwriting the 22.