File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes order required Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "order required" Watch "order required" New topic

order required

Rauhl Roy
Ranch Hand

Joined: Aug 01, 2006
Posts: 401

may i know how it is printing 1,0

when f1(i) is called i=0, but it is calling f1(i) with i=0, and when controller comes back i=0 without even telling i's values.

please let me know how this program is giving 1,0 output.
Joel McNary

Joined: Aug 20, 2001
Posts: 1824

Not sure I can explain in beginner's language, but basically it's all about order of operations and how stack-based computing works.

Here's what's going on:

Line 8: i is set to zero

Line 9: i = i++ + fl(i)

Evaluation order of the right-hand-side is left to right, so:

i++ : the value of i is pushed onto the stack, and then i is incremented by 1
i is now 1, and the stack is {0}

fl(i) is evaluated, with i equal to 1. This prints the "1," and then returns zero
The return value of the function is placed onto the stack

i is now 1, and the stack is {0, 0}

The addition operation is now evaluated, popping the first two values off of the stack and adding them together
0 and 0 are popped and added, resulting in a value of 0.

This value is pushed onto the stack as the total value of the right hand side.

The assignment then takes place, setting i to the value of the right hand side, which is 0
i is now 0, and the stack is irrelevant for our purposes.

We now print the value of i, which is 0.

End result is we've printed 1,0

Piscis Babelis est parvus, flavus, et hiridicus, et est probabiliter insolitissima raritas in toto mundo.
fred rosenberger
lowercase baba

Joined: Oct 02, 2003
Posts: 11957

but it is calling f1(i) with i=0

this is an incorrect statement..

There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Rauhl Roy
Ranch Hand

Joined: Aug 01, 2006
Posts: 401

that is absolutely correct to call Mr. fred rosenberger
I agree. Here's the link:
subject: order required
It's not a secret anymore!