SamDJava
SamDJava

Reputation: 267

Explanation of the output of Java code - postIncrement operator

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

Answers (4)

Ruchira Gayan Ranaweera
Ruchira Gayan Ranaweera

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 1

When System.out.println("Output"+ (i += i++)); 2345

when System.out.println("Output Step 2"+ i); 6

You can try this with Jeliot

Upvotes: 3

Dhanushka Gayashan
Dhanushka Gayashan

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

BackSlash
BackSlash

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

ToYonos
ToYonos

Reputation: 16843

In my opinion, the first i++ is erased by the assignation i += i++.

Upvotes: 2

Related Questions