How does the increment operator behave in Java?

Why is the result 8, not 9?

By my logic:

  • ++x gives 4
  • 4 + 4 gives 8, so x = 8
  • But after that, statement x should be increased by x++ , so it should be 9.

What is wrong with my logic?

 int x = 3; x = x++ + ++x; System.out.println(x); // Result: 8 
+5
source share
2 answers

You should notice that the expression evaluates from left to right:

The first x++ increments the value of x, but returns the previous value of 3.

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

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

However, even if you change the expression to

 x = ++x + x++; 

you still get 8

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

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

+21
source

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

+1
source

Source: https://habr.com/ru/post/1235093/


All Articles