What will be the result and why

Int i=10;
i=i++;
System.out.println(i);

Questions by Arnab.infinity   answers by Arnab.infinity

Showing Answers 1 - 57 of 57 Answers

poonamjava

  • Apr 1st, 2008
 

i will be 10

because i=i++;
if u break it
i=i; //1 step
here we are assigned the value and same variable.

if u r taking some other variable like j
j=i++

now print System.out.print(i+"     "+j)
Ans:

i=11
j=10

redleader

  • Apr 16th, 2008
 

In C++ and other languages the answer will be 11

Somehow it is 1=10. What should be noted is that i never gets incremented to 11.

int i=10;i=i++;System.out.println(i);

should not be logically different from

int i=10;
i=i;
i++;
System.out.println(i);

but in java somehow, it is logically different.

Post increment never occurs, or occurs but is discarded!!!!!!!!!!!!!!!!!!!!
This is a fundamental flaw in basic arithmatic in java!!!!!!!!!

  Was this answer useful?  Yes

redleader

  • May 2nd, 2008
 

Well it is still wrong. It shows that Java and references are not what they really seem. Its as though a copy is made somewhere and that is incremented, but not the original value.

Ignoring an increment when one has been explicitly defined, is not acceptable, and must be a fundamentaql design flaw. More coreectly, its probably a side effect of how fundamental variables are handled.

Complex, I can accept. Fundamental flaw, I can not.

Java references are another hidden aspect of the language. No object is ever passed by reference!
Its more like copies are passed, pass by value!



  Was this answer useful?  Yes

eleven is the correct answer
i=i++;

the above statement is equivalent to
i=i;                             //here i is 10
i=i+1;                         //here i is 11

so print statement will print 11 only

  Was this answer useful?  Yes

The answer is 10. What is distressing is the lack of understanding that some have as to why this is so. The value of 'i' is incremented, but the value that is returned by post increment is the original value. Since assignment is right associated, the value 10 is assigned to i (on the left side). AFTER it the post increment has been evaluated thus masking the fact that it has indeed occurred.

  Was this answer useful?  Yes

Yes this is similar to
temp = i;
i = i+1;
i = temp;
It will restore the value 10 since post increment. If its pre-increment last assignment will be i = temp+1

  Was this answer useful?  Yes

11, because even it is post increment, it will increment by 1 when it is going to reach println() statment, for the first statement(i++;) it wont increment, after completing the execution of this method i incremented by 1 and prints the result.

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions