Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Why the result is 1,0

 
weyman tan
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why the result is 1, 0 in following code



is any one tell me why, thank you very much

 
John Jai
Rancher
Posts: 1776
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Saloon Keeper
Posts: 3159
33
Google App Engine Java Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
so the result is 0,1

Should it give 1,0

John
 
O. Ziggy
Ranch Hand
Posts: 430
Android Debian VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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: 12181
34
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic