Pre and Postfix Increment

127 Views Asked by At
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.

3

There are 3 best solutions below

0
On BEST ANSWER

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.

Let us go step by step:

a = 1

set the variable a to 1; Now:

int a2 = a++;

will be equivalent to:

int a2 = a;
a++;

first assigned and only then increment, hence the output:

The value of a is 2
The value of a2 is 1
The value of a2 is 1

and the name postfix increment.

For the behavior that you want use ++a instead, namely:

int a = 1;
int a2 = ++a;
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);

Output:

The value of a is 2
The value of a2 is 2
The value of a2 is 2

In this case :

int a2 = ++a; is equivalent to :

 a++;
 int a2 = a;
0
On

The prefix and postfix increment only matter within the statement you are executing. Try adding prefix and postfix increments in the print statement.

0
On

that is how the post increment operator is designed to work...

doing

int a2 = a++;

is equivalent to doing

int a2 = a;
a = a + 1;

so your code is producing this output:

----------Test 3 ----------
The value of a is 2
The value of a2 is 1
The value of a2 is 1