-1

Can somebody explain why output of the code below is 1.

int i = 1;
i=i--;
System.out.println(i); // 1
Roman C
  • 48,723
  • 33
  • 63
  • 158
Sudz
  • 4,178
  • 1
  • 16
  • 24

1 Answers1

5

i-- does the following steps:

  • return the value of i
  • decrement i by 1

so the statement i = i-- does the following:

  • i is returned (the statement now equals i = 1)
  • i is decremented (i is now 0)
  • the statement (the assignment) is now done (i = 1)

In the end i is 1


To make it a bit more clear you could say the line i = i--; does pretty much the same as this code:

int j = i;
i = i-1;
i = j;
ParkerHalo
  • 4,262
  • 9
  • 27
  • 49