r/javahelp • • Oct 08 '18

I cant wrap my head around this piece of code

int i=3, j=5;

int k = (i++)+j;

System.out.println(i + " " + j + " " + k);

I feel pretty dumb because it outputs 4 5 8

I was sure it would output 3 5 9

23 Upvotes

15 comments sorted by

11

u/psikosen Oct 08 '18

Here I'll give you a clue, print after each declaration/statement, that's usually what I do if I get stuck. You'll get it, it not leave a comment.

4

u/BeakLee1 Oct 08 '18

thanks! I get how the increment works now for 4 instead of 3

still stumped on how k =8

I end up with 4 5 9

21

u/diMario Oct 08 '18

Perhaps I can solve your mystery. The increment operator is applied to the operand after it has been used in the other calculations. So in

int  k = (i++) + j;

first the value of i+j is calculated and put in k, and then the value of i is incremented.

There is a second form of the increment operator which increments the value of i before using it in a calculation. It is expressed by placing it in front of the operand, like this:

int  k = (++i) + j;

When you use this second statement in your program, you'll find that k indeed equals 9.

12

u/BeakLee1 Oct 08 '18

Thanks for the detailed response! It's a whole lot clearer now!! :)

3

u/psikosen Oct 08 '18

Great, didnt want to reveal that part just yet, but this same issue has burnt me a million times in other ways. Spaces can save your future self from you past self. When its 4am and your debugging after an all nighter. Glad you got it :) keep pushing it !! Well done.

1

u/winespring Oct 08 '18

What is the difference between ++i and i++?

7

u/randomfloridaman Oct 08 '18

i++ does the operation and then increments. ++i increments before it does the operation

1

u/winespring Oct 08 '18

i++ does the operation and then increments. ++i increments before it does the operation

Yes, but just saying that is too close to just giving him the answer.

5

u/randomfloridaman Oct 08 '18

Huh. I thought you we're asking for the answer. I didn't want to leave it ambiguous

-5

u/BeakLee1 Oct 08 '18

i++ increments the value of i by one and ++1 decrements i by 1

4

u/winespring Oct 08 '18

i++ increments the value of i by one and ++1 decrements i by 1

This is the source of your confusion, take a second look at those operators.

1

u/BeakLee1 Oct 08 '18

Thank you!

0

u/OffbeatDrizzle Oct 08 '18

this is wrong

3

u/nevergotcompiled Oct 08 '18

Int i is incremented after the sum has been made. If it was ++i then k would be equal to 9 since i was incremented before the sum.

1

u/jhayer_ Oct 31 '18

The ++ is after the i so java executes it at the end after 3 + 5 has been done and this doesn’t effect the answer since i has already been added.