2

Why is the output 25?

// CODE 1 public class YourClassNameHere { public static void main(String[] args) { int x = 8; System.out.print(x + x++ + x); } } 

Hi!

I am aware that the above code will print 25. However, I would like to clarify on how x++ will make the statement be 8 + 9 + 8 = 25.

If we were to print x++ only as such, 8 will be printed while x will be 9 in-memory due to post incrementation.

// CODE 2 public class YourClassNameHere { public static void main(String[] args) { int x = 8; System.out.print(x++); } } 

But why is it that in code 1 it becomes 9 ultimately?

I thank you in advance for your time and explanation!

2 Answers 2

5

Here is a good way to test the reason that equals to 25 is because the third x is equal to 9.

public class Main { public static void main(String[] args) { int x = 8; System.out.println(printPassThrough(x, "first") + printPassThrough(x++, "second") + printPassThrough(x, "third")); } private static int printPassThrough(int x, String name) { System.out.println(x + " => " + name); return x; } } 

Result

8 => first 8 => second 9 => third 25 
Sign up to request clarification or add additional context in comments.

5 Comments

Wow this is a really great answer! You can also look at mine if you get bored!
@TimBiegeleisen thanks Tim for your breakdown as well! Up-ed both your replies!
@Sam you might consider putting in a string as a second argument of printPassThrough and include in the println, so the evaluation order is apparent. E.g. printPassThrough(x, "first") => 8 first.
@AndyTurner edited with your recommendations.
to obtain number order 8+9+8, expression should be like that: System.out.println(print(x, "->first") + print(++x, "->first") + print(--x, "->third"));
0

I think it's worth of clarify:

x++ -> operate x , and then increment x (meaning x=x+1)

++x -> increment x (meaning x=x+1) , and then operate x

x-- -> operate x , and then decrement x (meaning x=x-1)

--x -> decrement x (meaning x=x-1) , and then operate x

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.