Win a copy of Kotlin in Action this week in the Kotlin forum!
programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering Languages Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# Why the result is 1,0

weyman tan
Greenhorn
Posts: 3
Why the result is 1, 0 in following code

is any one tell me why, thank you very much

John Jai
Rancher
Posts: 1776
Hello Weyman, welcome to the Ranch

An outer class cannot be declared static, so the code won't compile itself. I have removed it.

The questions tests the post fix and prefix increment operators. I have commented alongside the program the values and why it's printed so. The output I get is 0,2,1.

Next time while posting please UseCodeTags...

weyman tan
Greenhorn
Posts: 3
After see your answer, I know why and the original code is

so the result is 0,1

in order to study why, I add some code in it which result is 0,2,1.
However thank you very much

Mohamed Sanaulla
Bartender
Posts: 3179
34
Hi Weyman, I have added the code tags for you. Please post your code within the code tag. This makes the code more presentable.

John Stark
Ranch Hand
Posts: 185
so the result is 0,1

Should it give 1,0

John

O. Ziggy
Ranch Hand
Posts: 430
John Jai wrote:Hello Weyman, welcome to the Ranch

I dont understand where the 1 is coming from. When it gets to this point

i = i++ + f1(i);

i is 1. So if f1 returns 0, should shouldn't i be 2 because of the i++? i.e. the output to be 0,2,2? See comments below

fred rosenberger
lowercase baba
Bartender
Posts: 12542
48
I dont understand where the 1 is coming from. When it gets to this point

i = i++ + f1(i);

i is 1. So if f1 returns 0, should shouldn't i be 2 because of the i++? i.e. the output to be 0,2,2? See comments below

This more or less simplifies to

i = i++;

and we have a FAQ on why that leave i how it was...but basically, assuming i is one before we get to this line

1) we have a post-fix operator, so get the value of i. It is 1. Remember that value for a moment.
2) We now increment i, making it 2.
3) We now assign THE VALUE WE REMEMBERED to i. the value was 1, so assign 1 to i
4) i is now 1.

So for a brief, brief instant, after the increment operator but before the assignment, i IS equal to 2, but we then reset it back to 1.

 It is sorta covered in the JavaRanch Style Guide.