CODE
class Lifetime
{
public static void main(String arg[])
{
for(int x = 0; x < 3; x++)
{
int y = -1; // LINE A
System.out.println( "y is : " + y );
y = 100;
System.out.println( "y is now : " + y ); // LINE B
}
}
}
y is : -1
y is now : 100
y is : -1
y is now : 100
y is : -1
y is now : 100
When the for
loop executes first iteration with x = 0
, the variable y
is declared and initialized to -1
. Later it is changed to 100
. But when the iteration is completed after LINE B
, the variable y
declared in the block goes out of scope or its lifetime ends. The value 100
stored in y
is gone. So when the iteration runs again with x = 1
, y
is declared again and initialized to -1
.
int y = -1;
in LINE A
above the for
loop i.e. and see that value of y
is retained between iterations. This is because y
is declared above the for
loop and its lifetime does not end after LINE B
and so it continues to store the previous value 100
.