Question

    public static void main(String[] args) {
    int a = 1;
    int b = a++;

    System.out.println(b);
}

Why does the code above print 1? I was told that a++ means you would get the value of a. then increment it. But the code above never incremented a and just printed 1. Could someone please explain what is going on here?

Was it helpful?

Solution

It works as expected; Here is the code explained:

public static void main(String[] args) {
    // a is assigned the value 1
    int a = 1;
    // b is assigned the value of a (1) and THEN a is incremented.
    // b is now 1 and a is 2.
    int b = a++;

    System.out.println(b);
    // if you had printed a here it would have been 2
}

This is the same code but with pre-increment of a:

public static void main(String[] args) {
    // a is assigned the value 1
    int a = 1;
    // a is incremented (now 2) and THEN b is assigned the value of a (2) 
    // b is now 2 and so is a.
    int b = ++a;

    System.out.println(b);
    // if you had printed a here it would have been 2 so is b.
}

OTHER TIPS

int b = a++ is equivalent to int b = a; a += 1. When you print b, a==2 && b==1

a++ is like saying a-then increment a by 1. So after you say b = a++, b = 1 and a = 2.

If you were to preincrement b = ++a, you would get b = 2 Preincrement increases before it assigns value.

Conclustion

a++ assign value before incrementing
++a increments, then assigns value.

The reason is is as follow.

If it is i++, then equalent code is like this.

result = i;
i = i+1;
return result


If it is ++i. then the equlent code is like this.
i=i+1;
result =i;
return i

So considering your case, even though the value of i is incremented, the returned value is old value. (Post increment)

Post Increment Meaning = First complete assignment then Increment. Pre Increment Meaning = First Increment then assign .

ex:

int a=0,b;
b=a++; // ie. Step1(First complete assignment): b=0, then a++ ie a=a+1; so a=1 now.
System.out.println(b); // prints 0
System.out.println(a); // prints 1

if

int a=0,b;
b=++a; // ie. Step1(First Increment ): a++ ie a=a+1; so a=1 now, b=a , ie b=1.
System.out.println(b); // prints 1
System.out.println(a); // prints 1
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top