Originally posted by Sangeeta Sharma:

Hi Frns,

I am writing a simple program and got confused with a small fragment of code.I am writing that code fragment pls clarify the confusion.

int i=10;

int k=0;

i = ++i;

i = i++;

System.out.println(i);

this will print value as 11

and if the same program is written as

Int i=10;

int k=0;

k = ++i;

k = i++;

System.out.println(i);

this will print i as 12

why is there disprecency in the answers

Hi Sangeeta,

There is no discrepancy in the answers. The answers are absolutely correct.

Why ? Here's why...

When u say ++i, u can segregate this operation into 3 separate operations :

i += 1;

result = i;

return result;

Thus in the first program, when u say i = ++i, u get the value of i as :

i += 1 //i.e..11;

result = i //i.e..result = 11

return result; //i.e..return 11;

This value returned (11) is then stored into i. So new value of i becomes 11.

Now when u use the operation i++, u can consider 3 operations again:

result = i;

i += 1;

return result;

So in the next line of the first program, when u say i = i++, u get:

result = i //i.e..result = 11 since i got the new value 11 from the previous step.

i += 1 //i.e..i = 11+1 = 12.

return result //i.e..return 11

Hope u understood that !!

Now coming to the next program lines with variable 'k':

Keeping the above 3-line operations in view, we have k = ++i;

So,

i += 1; //i.e..i=11

result = i; //i.e..result = 11

return result // return 11;

So k = 11.

and the next statement :

k = i++ yields

result = i; //i.e..result = 11 since i is 11 from previous step

i += 1; //i.e..i = 12;

return result; //i.e..return 11

this final value 11 is stored in k.

Hence i=11 and k=11 from first step

and i=12 and k=11 from second step.

Hope this gets ur fundas absolutely crystal clear !!

Cheers !!