javasyntaxincrementpost-incrementpre-increment

Java: Order of Operations, Post-Increment Clarification


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!


Solution

  • 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