java - Why static variable not behaving the way it should be during finally -
this question has answer here:
as far know, in case of static variables if value changed in 1 place reflected in places. example
static int i=0; public static void test1() { system.out.println(i); i=100; } public static int test2() { return i; }
sysout of test1()--0 sysyout of test2()=100; again sysout of test1()=0
i clear on point.
but not clear on below code
public static int test() { try { = 2; system.out.println("before "+i); return i; } { = 12; system.out.println("in finally"); } }
then why print 2 though value of static changed 12; below sequence of method calls;
test1(); system.out.println(test2()); test1(); system.out.println(test());
outputs
0 100 100 before 2 in 2
edit
when debug, found flow try block->finally block->try blocks return statement. in case before control goes return statement,finally block executed.so means value of 12 why did not return 12
you print out return value of test()
last thing do, not i
.
when return i
executed, i
evaluated. @ point doing return 2;
. since i
evaluated 2, changing in block doesn't affect evaluated value in return statement.
if do
system.out.println(test()); system.out.println(i);
you'll see i
12.
see this more information.
Comments
Post a Comment