2

I am learning java and this logic makes me feel confused.

Isn't here i=20(+1)+20(+1)?

Why 41 instead of 42?

jshell> int i = 20
i ==> 20
jshell> i=i++ + i++
i ==> 41

See this code run at Ideone.com.

Nikolas Charalambidis
  • 40,893
  • 16
  • 117
  • 183
Jack
  • 23
  • 3
  • 5
    No, `++` does NOT mean `+1`. It means "use the _current_ value of this variable, but increase it so that _next_ time you use the variable, it stores something different". – Dawood ibn Kareem Sep 23 '22 at 03:46

1 Answers1

2

Effectively, the expression i=i++ + i++; is equal to i=i++ + i;. Why? The latter i++ result value is never used and is not propagated. The result of the postfix addition i++ is used as long as the value i is added later in the expression and the result takes the effect. However, after the latter i++ the result value of i is not used.

If you want to achieve the result of 42, you need to perform the postfix assignment (i++) after the whole result is assigned back to the i variable:

int i = 20;
i = i++ + i;
i++;
System.out.println(i);
Nikolas Charalambidis
  • 40,893
  • 16
  • 117
  • 183
  • 1
    The correct statement should be, if you want to achieve the result of `42`, you should write down your actual intention, `i = i + 1 + i + 1;` There is no reason to use `++` here at all. – Holger Sep 23 '22 at 08:38
  • I wanted to demonstrate how the `i++` works. Of course, `i + 1 + i + 1` or even `2 * i + 2` would be better in a production code. – Nikolas Charalambidis Sep 23 '22 at 08:54