Reputation: 267
I am looking for the answer to the backend logic for the code.
int i=4;
System.out.println("Output"+ (i += i++));
System.out.println("Output Step 2"+ i);
The answer is 8 in both cases. Now for the first step the answer 8 is very natural as i += i++
translates to i = i + i++
;.
As i++
is the post increment operator it should increase the value to 9 in step 2. What is the flaw in my understanding?
Upvotes: 1
Views: 168
Reputation: 35597
System.out.println("Output"+ (i += i++)); // sum will be 8, i=8
Then post operator of i++
not take any effect because of the summation happen before that.
Make sure that Java
passed by value.
Actually what happen?
when int i=4
When System.out.println("Output"+ (i += i++));
when System.out.println("Output Step 2"+ i);
You can try this with Jeliot
Upvotes: 3
Reputation: 734
When you use the "i += i++", exist value of the i variable is adding to the itself before increment it from 1. After adding the value then increase the value from 1. That is why System.out.println("Output"+ (i += i++)); is showing "Output 8" as the output.
Also if you use i++, that change is not affect to the original variable. That is why you get same result at the second output also.
Upvotes: 2
Reputation: 22243
Your code is equivalent to:
int i=4;
int temp = i + i; // 8
i = i + 1;
i = temp; // still 8
System.out.println("Output"+ i); //8
System.out.println("Output Step 2"+ i); //8
Hence the result is 8
in both cases.
Upvotes: 2
Reputation: 16843
In my opinion, the first i++ is erased by the assignation i += i++.
Upvotes: 2