Postfix increment operator in JAVA

46 Views Asked by At

I'm studying about postfix increment operator in JAVA, and curious about why the result is 6 when coding like this.

int b = 3;
b += b++;
        
System.out.println(b);

I think that due to the += operator, 3 is added to b, making it 6,
and then due to the ++ operator, 1 is added to 6, resulting in b being 7.
But the compile result showed me 6.

Can someone explain why my understanding is incorrect?

1

There are 1 best solutions below

0
Sarah Nasser On

We declare the variable b and initialize it to 3.

Then we have this line, b += b++;

Let's dissect it.

You are correct that b++ deals with the postfix increment operator. However, note that b gets incremented after we take the value of b (this is the case in which we are dealing with the postfix increment operator!).

So, the right hand side is really 3 because the value of b is 3 and we increment b after ("post") getting this value.

So, the whole expression is really just b += 3.

We are incrementing the value of b by 3, so b = 6.

Then, remembering that since we have the postfix increment operator, we will then have to increase b by 1, only on the right hand side (not on the whole expression).

However, we will not again do b += 1 on the whole expression, so b = 6 at the end of this program.

If you want to continue writing this program such that we will increment b again, please feel free to do so. Since the prefix increment operator can be contrasted with the postfix increment operator, why don't you try a sample program with that (if you haven't already) and understand it?

If anything I said confused you, please comment on this!