a = 1;
int a2 = a++;
System.out.println("----------Test 3 ----------");
System.out.println("The value of a is " + a);
System.out.println("The value of a2 is " + a2);
System.out.println("The value of a2 is " + a2);
The result is :
----------Test 3 ----------
The value of a is 3
The value of a2 is 2
The value of a2 is 2
I don't understand why the value of a2
does not increase after the second output. Even a
is increased using postfix increment and assigned to a2
. Please explain it to me.
Let us go step by step:
set the variable
a
to 1; Now:will be equivalent to:
first assigned and only then increment, hence the output:
and the name postfix increment.
For the behavior that you want use
++a
instead, namely:Output:
In this case :
int a2 = ++a;
is equivalent to :