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 Answers2

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
Sam Orozco
  • 1,258
  • 1
  • 13
  • 27
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