this question has answer here:
when try execute following function in java:
public static int myfunc (int x) { try { return x; } { x++; } } public static void main (string args[]) { int y=5,z; z = myfunc(y); system.out.println(z); } the output printed on console 5, 1 expect 6 printed. idea why?
...would expect 6 printed. idea why?
the x++ happens after value 5 has been read x. remember follows return statement expression. when return statement reached, expression evaluated (its value determined), , resulting value used function's return value. in myfunc, here's order of happens:
- enter
tryblock. - evaluate expression
x(e.g., value ofx). - set value function's return value.
- enter
finallyblock. - increment
x. - exit function using return value step 3.
so of when leave function, though x 6, return value determined earlier. incrementing x doesn't change that.
your code in myfunc analogous this:
int y = x; x++; there, read value of x (just return x does), assign y, , increment x. y unaffected increment. same true return value of function.
it might clearer functions: assuming foo function outputs "foo" , returns 5, , bar function outputs "bar", code:
int test() { try { return foo(); } { bar(); } } ...executes foo, outputting "foo", executes bar, outputting "bar", , exits test return value 5. don't expect function wait call foo until after finally occurs (that strange), , indeed doesn't: calls when reaches return foo(); statement, because evaluates expression foo(). same true of return x;: evaluates expression , remembers result of statement.
Comments
Post a Comment