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?
We declare the variable
band initialize it to3.Then we have this line,
b += b++;Let's dissect it.
You are correct that
b++deals with the postfix increment operator. However, note thatbgets incremented after we take the value ofb(this is the case in which we are dealing with the postfix increment operator!).So, the right hand side is really
3because the value ofbis3and we incrementbafter ("post") getting this value.So, the whole expression is really just
b += 3.We are incrementing the value of
bby3, sob = 6.Then, remembering that since we have the postfix increment operator, we will then have to increase
bby1, only on the right hand side (not on the whole expression).However, we will not again do
b += 1on the whole expression, sob = 6at 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!