Menu
Topics Index
...
`


Control Statements > Blocks of code >
Siva Nookala - 12 Apr 2016
Lifetime of a variable in Java defines how long a variable and its value are valid.

Lifetime of variable
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
        }
    
    }
}
OUTPUT

y is : -1
y is now : 100
y is : -1
y is now : 100
y is : -1
y is now : 100

DESCRIPTION

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.

THINGS TO TRY
  • Move the declaration 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.

0
Wrong
Score more than 2 points

© meritcampus 2016 - 2017

All Rights Reserved.