I am confused as to why c = 8 and not 9 in the code below.
int a = 5, b = 3;
System.out.println(a + b);
int c = a + b++; //
b++;
System.out.println(a + b);
System.out.format("a=%d, b=%d, c=%d %n", a,b,c);
I am confused as to why c = 8 and not 9 in the code below.
int a = 5, b = 3;
System.out.println(a + b);
int c = a + b++; //
b++;
System.out.println(a + b);
System.out.format("a=%d, b=%d, c=%d %n", a,b,c);
Post-increment (b++)
or decrement (b--)
means read the value first then modify. Pre-increment(++b)
or decrement (--b)
means modify the value then read.
When you say b++
, you are not saying 'add 1 to b
, and then use b
's new value'. You are saying 'use b
's current value for this expression, and then once you are done, add 1 to b
'.
So in your example, int c = a + b++
, the current expression is a + b
. So, for the a + b
, b
will give the expression 3
, then increment itself to 4
.
If you want to avoid this issue, you could do ++b
instead of b++
. ++b
will do exactly what you expect: increment b
, then use its new value in the expression.
The assignment of b
is taking place after the statement.
int c = a + b++;
This is the same as saying
int c = a + b;
b = b + 1;
If you wanted c
to equal 9
, you can use the prefix unary operator.
int c = a + ++b;
Which is the same as saying
b = b + 1;
int c = a + b;
There are two types of increment Operators :
In your case you are using b++
hence, it first use the value of b, i.e. 3, and then updates 3 -> 4, and again you are using b++
, again it update the value to 4 -> 5. Hence its new value is 5 and in c it used the previous value not updated.