With the declaration of every variable in Java, a natural question arises as soon as the variable is declared, “How long this variable be around ?” This question is answered by the Scope of Variable.
All the variables in Java have their scope or which may be called as the ‘Expiry date of a variable’
In terms of the Scope of Variable, we can classify the Java variables in 4 parts :
- Static Variables
Static variables have the longest scope among all. They are created when a class is loaded
and survives as long as the class stays loaded in the Java Virtual Machine (JVM)
- Instance Variables
They are next most lived variables. They are created when a new Instance is created and
survives until the instance is removed.
- Local Variables
Unlike Objects and Instance variables, Local variables are stored in the Stack of the
memory. These variables lives as long as the methods in which they are declared, remains
on the stack.
However, we can have local variables alive and still out of scope. For more information please read, Errors due to Scope of Variable.
- Block Variables
These variables are those which are defined within ‘for’ block or ‘if-else’ block. There scope
ends as soon as the command comes out of the block.
A programmer must take care of the errors which appears due to calls to the variables when the command goes out the Scope of Variable. One common mistakes occurs when one variable is shadowed and two scopes overlap. For learning more on shadowing, please read Errors due to Scope of Variable.
References :
1. Scope of Variables : http://ezdia.com/Scope_of_Variables_in_Java/Content.do?id=1300
2. Java Static Variable : http://ezdia.com/Java_Static_Variable/Content.do?id=1301
