Consider the following code
int val1 = 3;
val1++;
int val2 = val1++;
System.out.println(val1);
System.out.println(val2);
Val1 value = 5;
Val2 value = 4;
Why is the value of Val1 "5"?
As I understand it it should be 4, because:
at line1 it is assigned value of 3, on line2 1 gets added by way of val1++ which result in val1 being 4.
Val2 is the value of val1 thus 4, plus 1 which is 5
HOwever the compiler gives val1 a value of 5 and val2 a value of 4, what am I not understanding or missing here?
I realize val1++ is used a second time but it is assigned to val2, and should not effect val1s value, or am I wrong?
解决方案
a++ is known as postfix.
add 1 to a, returns the old value.
++a is known as prefix.
add 1 to a, returns the new value.
so int val2 = val1++; will return the old Value (4)
and still add one to val1