Scope of Variable
Scope of Variable
1. Instance Variables
2. Class Variables (Static)
3. Local Variables
Now, let us dig into the scope and lifetime of each of the above mentioned type.
1. Instance Variables
A variable which is declared inside a class, but is declared outside any methods and blocks is
known as instance variable.
A variable which is declared inside a class, outside all the blocks and is declared as static is
known as class variable.
3. Local Variables
All variables which are not instance or class variables are known as local variables.
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-1
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.
Example-2
public class scope_and_lifetime
{
int num1, num2; //Instance Variables
int result;
int add(int a, int b)
{
//Local Variables
num1 = a;
num2 = b;
return a+b;
}
public static void main(String args[])
{
scope_and_lifetime ob = new scope_and_lifetime();
result = ob.add(10, 20);
num1 = 10;
System.out.println("Sum = " + result);
}
}
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.
Example-3
Summary