You are being forwarded to the lastest updates ot his page!
Or you can Click Here if it doesn't work or you don't wish to wait.

Sample Question

David Chan
Dear all,

I don't understand one sample question can anyone help me?

What will be print in the following code?

amethod() {
int i=0;
i = i++;
i = i++;
i = i++;
System.out.println(i);
}

The Answer is 0 will be printed.

Thanks.

David Chan


rajashree ghatak
hi david,

ur code is based on post-increment concept.
int i=0;
i=i++;
i=i++;
i=i++;
here variable i has been initialized to 0.In the 2nd statement,the value of i(ie. 0 )is assigned to i before i is incremented to 1.so now i will have 0 as its value.Again in the 3rd statement,the value of i(ie. 0) will be assigned to i before i is incremented to 1.so now i will have 0 and not 1 as its value.This process is continued for the 4th statement also.
Hence 0 gets printed.

if it had been the case of pre-increment like the below:
int i=0;
i=++i;
i=++i;
i=++i;
System.out.println(i);

then 3 would be the output since the value of i is incremented by 1 in all the 3 statements before being assinged to variable i again.

Hope this will help.
rajashree.



Paul Anil
Answered here: http://www.jdiscuss.com/index.jsp?pg=VP&tab=discuss&fid=2&tid=2

-Paul.

------------------
Get Certified, Guaranteed!
(Now Revised for the new Pattern)
www.enthuware.com/jqplus

Your guide to SCJD exam!
www.enthuware.com/jdevplus

Try out the world's only WebCompiler!
www.jdiscuss.com


David Chan
First of all, thank rajashree ghatak and Paul Anil reply me. However, sorry for my stupid. I still don't understand.

After run the following code,

int i = 0;
int j = 0;

i = j++;

The result will be i = 0 and j = 1.

So, I think for the follow code, the result is the similar :

int i = 0;

i = i++;

i will be assigned with 0 then i increase by 1 then the result of i become 1.

I don't understand what different in the 2 situations.

Thanks

David Chan


Jane Griscti
Hi David,

With post-increment operators, Java evaluates the variable before the increment occurs. With the example i = i++, i on the right side of the assignment is evaluated as '0'; the post-increment value 0+1 is stored as the new value for 'i' then the assignment takes place i = 0 ... this effectively overwrites the previously stored value of '1'.

Hope that helps.

I'm going to move this over Certification Study as it is not related to Results.

------------------
Jane Griscti
Sun Certified Programmer for the Java™ 2 Platform