Search code examples
javapostfix-operatorprefix-operator

Pre and Postfix Increment


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.


Solution

  • 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;