This question already has an answer here:
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.
i++
is the post-increment operator, which has expression value the old value of i
, but a side-effect of incrementing i
. The value is 1
, but it leaves i
changed to 2
.
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
When this code runs:
public static void main(String[] args) {
int i = 0; //i=0;
System.out.print(++i); // increments i to i=1, and prints i
System.out.print(i++); // prints i and then increments it to i=2
System.out.print(i); // prints i, i.e. 2
}
i is initially 0, then it is pre-incremented and printed so you have the first 1, then it is printed again and you have the second 1, then post-incremented, then printed for the last time and you have the 2
Simply;
In post increment, the increment is done after the variable is read.
In pre increment, the variable value is incremented first, then used in the expression.
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.
来源:https://stackoverflow.com/questions/16506147/semantics-of-pre-and-postfix-operator-in-java