// Scope and Lifetime Quiz. What is the expected output of this program? // // Written 2001 by Wayne Pollock, Tampa Florida USA. class ScopeTest { public static void main ( String [] args ) { for ( int i = 0; i < 10; ++i ) { int j = 2; ++j; System.out.println( j ); } } }
In this program, the local variable j
has the same scope
as i
(the body of the for
loop) but a different
lifetime.
i
comes into existance at the begining of the for
loop, and goes away only when the loop exits.
In contrast, j
comes into existence and goes
away each iteration of the loop.
The program below thus prints out ten "3
"s,
not "3 4 5 6 7 8 9 10 11 12
".
Send comments and questions to
pollock@acm.org. |