0

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);
    
    
user207421
  • 305,947
  • 44
  • 307
  • 483

4 Answers4

6

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.

WJS
  • 36,363
  • 4
  • 24
  • 39
2

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.

user207421
  • 305,947
  • 44
  • 307
  • 483
davidalayachew
  • 1,279
  • 1
  • 11
  • 22
1

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;

Assignment, Arithmetic, and Unary Operators (The Java™ Tutorials > Learning the Java Language > Language Basics)

Reilas
  • 3,297
  • 2
  • 4
  • 17
  • That's a good explanation! – Peter Mulm May 24 '23 at 12:10
  • 2
    “after the statement” is misleading at best. Compare with `int c = a + b++ + b++;`… – Holger Jun 05 '23 at 11:08
  • @Holger, I'm not sure I understand, can you provide an answer? – Reilas Jun 05 '23 at 16:46
  • 2
    When you try something like `int c = a + b++ + b++;` you’ll notice that the second `b` will evaluate to the updated value of the first `b++`. In other words, the `b` is not updated “after the statement” as other parts of the expression can see the already updated value. You should rather consider an expression like `b++` to be similar to calling `set(index, value)` on a `List` which will change the list immediately but return the old value. – Holger Jun 05 '23 at 17:44
0

There are two types of increment Operators :

  1. Post increment : (b++), which states that it will use the value first and then increment.
  2. Pre Increment : (++b), which states that it will first increment the value and then use it.

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.