This week's book giveaway is in the Testing forum.We're giving away four copies of The Way of the Web Tester: A Beginner's Guide to Automating Tests and have Jonathan Rasmusson on-line!See this thread for details.
Win a copy of The Way of the Web Tester: A Beginner's Guide to Automating Tests this week in the Testing forum!

# a tricky question

Senthil Nathan.s
Greenhorn
Posts: 11
eg:
int i=10;
i=++i;
i=i++;
System.out.println(i);

doubt:
I expect the answer to be 12 but the answer is 11.Can anyone explain me how this happens

Thanks and regards
S.Senthilnathan

Krishnan Loganathan
Greenhorn
Posts: 23
Hi senthilnathan,

when you issue the command
i = i++;

first it will assign the old value of 'i' (ie., 11) to the i and then it will add 1 to the old value.

so, when you print the i, it will print 11 only.

you just modify the code slightly as follows and test

int j = i++;
System.out.println("the value of i ==> " + i);

now it will print 12. because you are assiging the old value of i to the seprate variable 'j'.

Thanks & Regards,
Loga

Senthil Nathan.s
Greenhorn
Posts: 11
Thanks krishnan for your reply but anyhow the contents of i must be incremented by one know .You mean that the contents of i wont get incremented at all ,is it so.......

Murali Mohan
Ranch Hand
Posts: 66
int i=10;
i=++i;//1
i=i++;//2

The result of the prefix or postfix increment expression is not a variable, but a value.
For prefix or postfix increment the value 1 is added to the value of the variable and the sum is stored back into the variable.
The value of the prefix increment expression is the value of the variable after the new value is stored.
The value of the postfix increment expression is the value of the variable before the new value is stored.

in line 1 ++i evaluates to value 11
value of expression=11 & i=11
i=value of expression
in line 2 i++ evaluates to value 11
value of expression=11 & i=12
i=value of expression
=> i is overwritten with value 11

I think that solves your problem.

Balaji Sampath
Ranch Hand
Posts: 63
Excellent Explanation Murali..

Thanks
Balaji.S

Abhinav Srivastava
Ranch Hand
Posts: 354
I have seen hunderds of threads on this particular topic.
Mostly, the explanation given is 'reverse-engineered'.
Interestingly, if you do the same in C, you'll get 12 as your answer.
C != Java, but when you read the definition of the post-increment operator, do you find any difference?

marc weber
Sheriff
Posts: 11343
"Murali,"

Please revise your display name to meet the JavaRanch Naming Policy. To maintain the friendly atmosphere here at the ranch, we like folks to use real (or at least real-looking) names, with a first and a last name.

You can edit your name here.

Thank you for your prompt attention, and enjoy the ranch!

-Marc

Corey McGlone
Ranch Hand
Posts: 3271

Senthil Nathan.s
Greenhorn
Posts: 11
Thanks for your explanation Murali.I understood the concept very well.

Murali Mohan
Ranch Hand
Posts: 66
Thanks to all.