I wondering to know why this snippet of code give output 112
How this last digit 2 was creating?
public static void main(String[] args) { int i = 0; System.out.print(++i); System.out.print(i++); System.out.print(i); Why does this happen?
Your snippet it's translated as
int i = 0; i = i + 1; // 1 System.out.print(i); // 1 System.out.print(i); // 1 i = i + 1; // 2 System.out.print(i); // 2 That's why the final result it's a 2.
++i it's incrementing the variable before being called by the print method and i++ it's incrementing the variable after the method execution.
When we use post or pre increment operator it increases the value.
Post increment operator (i++) assigns the value first, then increments it. Pre increment operator (++i) increments first then assigns the value. They both behave like this :
int i=0; i=i++; System.out.println(i); //1 i=++i; System.ou.println(i); //1 You are applying two increments on i. The initial value was 0 so after two increments (++i and i++ )it will become 2.
Both i++ and ++i are incrementing the value of i by one.
They are similar to
i = i+1; but the ++i one increments the value of i then uses it, so 0 becomes 1 and printed out, while the i++ first uses the value and then increments the value of i, so the printed value is 1 and then it becomes 2 hence the last digit(the final value of i) is 2.
++imeans increment and readi,i++means read and incrementi, andimeans readi.