Search code examples
javajava-8unary-operator

What is the order of multiple pre/post incrementations in one line equation in JAVA?


I have this piece of code in JAVA 8:

int x=3; int y = --x + x++ + --x ; System.out.print("y: " + y + " x: "+x);

As I understand it should be split like this:

  1. y = 2 + x++ + --x; x = 2
  2. y = 2 + 2 + --x; x = 2
  3. y = 2 + 2 + 1; x = 1
  4. y = 5; x = 2

And it prints y: 6 x: 2 What is the order of operation in here?


Solution

  • It's because of the way pre and post increments work, it gets evaluated like this:

     1. y = --x + x++ + --x ;
     2. y = 2 + (2)++ + --(3);
     3. y = 2 + 2 + 2;
     4. y = 6
    

    After 2 decrements and 1 increment, x becomes 2.