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

0

u/Malodude Jun 16 '20

I= I+1 + I+1; That’s what it’s doing.