Adam Ary
Adam Ary

Reputation: 91

How does the increment operator behave in Java?

Why is the result 8 and not 9?

By my logic:

  1. ++x gives 4
  2. 4 + 4 gives 8, so x = 8
  3. But after that statement x should be increased due to x++, so it should be 9.

What's wrong with my logic?:

int x = 3;
x = x++ + ++x;
System.out.println(x); // Result: 8 

Upvotes: 5

Views: 391

Answers (2)

Burak Keceli
Burak Keceli

Reputation: 953

++x is called preincrement and x++ is called postincrement. x++ gives the previous value and ++x gives the new value.

Upvotes: 1

Eran
Eran

Reputation: 393771

You should note that the expression is evaluated from the left to the right :

First x++ increments x but returns the previous value of 3.

Then ++x increments x and returns the new value of 5 (after two increments).

x = x++ + ++x;
    3   +  5     = 8

However, even if you changed the expression to

x = ++x + x++;

you would still get 8

x = ++x + x++
     4  +  4   = 8

This time, the second increment of x (x++) is overwritten once the result of the addition is assigned to x.

Upvotes: 21

Related Questions