Scope and life time of variables
scope and life time of variables |
Scope determines the visibility of program elements with respect to other program elements. In Java, scope is defined separately for classes and methods:
1) variables defined by a class have a global scope
2) variables defined by a method have a local scope
A scope is defined by a block:
{
…
}
A variable declared inside the scope is not visible outside:
import java.io.*;
public class ScopAndLife
{
public static void main(String args[])
{
int n; //scope and life time of variables only within this block
}
n = 1;// this is illegal
Instance variables
Instance variables are those that are defined within a class itself and not in any method or constructor of the class. They are known as instance variables because every instance of the class (object) contains a copy of these variables.
Instance variables are those that are defined within a class itself and not in any method or constructor of the class. They are known as instance variables because every instance of the class (object) contains a copy of these variables.
Local variables
A local variable is the one that is declared within a method or a constructor (not in the header). The scope and lifetime are limited to the method itself.
One important distinction between these three types of variables is that access specifiers can be applied to instance variables only and not to argument or local variables.
In addition to the local variables defined in a method, we also have variables that are defined in bocks life an if block and an else block. The scope and is the same as that of the block itself.
- Variables are created when their scope is entered by control flow, and destroyed when their scope is left.
- A variable declared in a method will not hold its value between different invocations of this method.
- A variable declared in a block looses its value when the block is left.
- Initialized in a block, a variable will be re-initialized with every re-entry. Variables lifetime is confined to its scope!