Scope and Lifetime of a Variable in Java
One of the frequent questions, which any programmer comes across in the programming world
is, “What is the scope of this variable?” In this article, our main concern is to shed light
upon the scope and lifetime of a variable in Java.
The scope of a variable refers to the areas or the sections of the program in
which the
variable can be accessed, and the lifetime of a variable indicates how long the
variable
stays alive in the memory.
A joint statement defining the scope and lifetime of a variable is “how and where
the
variable is defined.” Let me simplify it further. The comprehensive practice for
the scope
of a variable is that it is accessible only inside the block it is declared.
Types of Variables and its Scope
There are three types of variables.
- Instance Variables
- Class Variables
- Local Variables
Now, let us dig into the scope and lifetime of each of the above mentioned type.
Instance Variables
A variable which is declared inside a class, but is declared outside any methods and blocks
is known as instance variable.
Scope: Throughout the class except in the static methods.
Lifetime: Until the object of the class stays in the memory.
Class Variables
A variable which is declared inside a class, outside all the blocks and is declared as
static is known as class variable.
Scope: Throughout the class.
Lifetime: Until the end of the program.
Local Variables
All variables which are not instance or class variables are known as
local variables.
Scope: Within the block it is declared.
Lifetime: Until control leaves the block in which it is declared.
Now, let us look at an example code to paint a clear picture and understand the concept
of scope and lifetime of variables better.
Example
Output
Let us look at the output of the above example code.
Here in the above example code, the variables num1 and num2 are Instance Variables. The variable result is Class Variable. The parameters of the method add, namely, ‘a’ and ‘b’ are Local Variable. Let us try and use the variables outside of their defined scope, and see what happens.
Output
Let us look at the output of the above example code.
See! We get an error. I removed the keyword static from the variable
result, which makes it
an instance variable. We cannot use instance variable inside a
static method, so the usage
of num1 inside public static void main(String args[]) gives an error.
Let us look at one more interesting concept.
Nested Scope
We can always use a block of code inside a block of code. This technique of programming is
known as nesting of blocks.
Scope: All the variables of the outer block are accessible by the inner
block but the variables within inner block are not accessible by the outer block.
Let us look at an example for the above case.
Output
Let us look at the output of the above example code.
As we have tried to access the variable “y” outside the block it is declared, we encounter an error.