Scope of Variables in Java
The scope of variables in Java is a location (or region) of the program where the variable is visible to a program and can be accessible.
In other words, the variable scope is the location from which we can access its value. The scope of variables determines its accessibility for other parts of the program.
Java allows declaring variables within any block. A block defines a scope that starts with an opening curly brace and ends with a closing curly brace.
There are three types of variables in Java, depending on their scope:
- local variables
- instance variables
- class variables (static variables).
Let’s understand the scope of all variables with the help of important example programs.
Scope of Local Variables in Java
Local variables are those variable which are declared inside methods, constructors, or blocks. These variables are accessible only within that specific block of code in which they are declared.
When we create a local variable inside a method, constructor, or block, its scope only remains within the method, block, or constructor. It is visible only within the method, constructor, or block.
As we exit from the method or block, the scope of a local variable is destroyed. Therefore, we cannot access it from outside the method, constructor, or block. We cannot also change its value from outside of any block.
Let’s take a very simple example in which we will define a local variable in a method and will try to access from the outside the block of method.
Example 1:
public class LocalVar
{
// Instance method declaration.
void m1() {
int x = 20; // local variable
}
public static void main(String[] args)
{
// Creating an object of class and call the local variable using reference variable.
LocalVar lv = new LocalVar();
System.out.println("Accessing local variable: " +lv.x); // compile time error.
}
}
In this example, we have tried to access a variable defined in the method m1(). Since it is a local variable, we cannot access it from the outside the block.
Example 2:
package variablePrograms;
public class School
{
// Declare instance variable.
public String name = "John";
// Declaration of constructor.
School()
{
int id = 1234; // block scope, only accessible within this constructor block.
System.out.println("Id of Student: " +id);
}
// Declaration of user-defined method in instance area.
public void mySchool()
{
// Declaration of local variable.
String schoolName = "RSVM"; // block scope, only accessible within this method block.
System.out.println("Name of School: " +schoolName);
}
public void mySchool2()
{
// This statement will generate a compile time error
// because we cannot access local variables from outside the method, constructor, or block.
System.out.println("Name of School: " +schoolName)
}
public static void main(String[] args)
{
// Create the object of class 'School'.
School sc = new School();
sc.mySchool();
}
}
Output: Id of Student: 1234 Name of School: RSVM
In the preceding example, we cannot access the local variable “schoolName” from outside the method mySchool2(). If we try to access it, we will get a compile-time error.
Let’s take one more example to understand the scope of local variable more clearly in Java.
Example 3:
package variablePrograms;
public class School
{
// Declaration of instance variable.
public String name = "John";
// Declaration of constructor.
School()
{
int id =1234; // local variable.
}
// Declaration of an instance method.
public void mySchool()
{
String schoolName = "RSVM"; // local variable.
}
public static void main(String[] args)
{
// Create the object of class 'School'.
School sc = new School();
// Calling the local variables from outside method and constructor.
System.out.println("Name of School: " +schoolName); // compilation error.
System.out.println("Id of Student: " +id); // compilation error.
}
}
Scope of Instance Variables in Java
Instance variables are those variable that are declared within a class but outside any method. They are associated with objects of the class and have distinct values for each object.
When we define an instance variable inside a class, its scope is within the class. It is visible inside all the methods, constructors, and from the beginning of its program block to the end of program block in the class.
Therefore, all the methods, constructors, and blocks inside the class can access an instance variable. Normally, it is recommended to make instance variables private in the class. However, the visibility of instance variables for the sub-classes can be given with the use of access modifiers.
In the user-defined method (instance method), we can access instance variables directly by calling the variable name inside the class. Within static methods and different classes, instance variables should be called using an object reference variable. It has the following general form:
ObjectReference.VariableName;
Let’s take an example program based on the scope of instance variables in Java.
Example 4:
package variablePrograms;
public class Calculation
{ // Block 1
// Declaration of instance variables.
int a = 20; // class scope
int b = 30; // class scope
// Construction declaration.
Calculation()
{ // Block 2.
int c = 50; // Local variable.
}
// Instance methods declaration.
void addition()
{ // Block 3.
int x = 100;
int add = a + b + x; // Here, variable a and b declared in block 1 are available to block 3.
System.out.println("Sum: " +add);
}
void subtraction()
{ // Block 4.
int sub = a + b + c; // Here, variables a and b are available to block 4, but variable c is not available to block 4 because c is local variable.
System.out.println("Sub: " +sub);
}
public static void main(String[] args)
{
Calculation c = new Calculation();
c.addition();
c.subtraction();
}
}
Output: Sum: 150 Exception in thread "main" java.lang.Error: Unresolved compilation problem: c cannot be resolved to a variable
The variable a and b declared in block 1 are visible to all blocks, but variable c is visible only for block 2 because of the local variable. That’s why we cannot access it inside the block 4.
Variables are created when their scope is started and destroyed when their scope is ended. It means that a variable defined within the block loses its value when the scope is ended. Thus, the lifetime of any variable is confined to its scope.
Let’s take an example where we will declare the instance and local variables with the same name and definition. Consider the following source code.
Example 5:
package variablePrograms;
public class ScopeTest
{
int num = 20; // instance variable
void m1()
{
int num = 30; // local variable
System.out.println("Number: " +num);
System.out.println("Number: " +this.num);
}
public static void main(String[] args)
{
ScopeTest st = new ScopeTest();
st.m1();
}
}
Output: Number: 30 Number: 20
In the preceding program, we have declared two variables, instance and local, with the same name and definition. First, instance variable num is declared with value 20, and second is local variable with the same name but with value 30.
The local variable num within m1() method hides instance variable num. Therefore, when we will call m1() method from the main() method, the output will be displayed num equal to 20, even though there is also a num instance variable that equals to 30. In this case, we can use this.num to call the instance variable. It will print the output 20.
Scope of Static Variables in Java
Static variables are those variables that are declared using the static keyword. These variables are also called class variables because they are associated with the class rather than with objects and their values are shared among all instances of the class.
When we define a variable with a static keyword inside the class, its scope is within the class. That is, the scope of a static variable is within the class.
All the methods, constructors, and blocks inside the class can access static variables by using the class name. It has the following general form:
ClassName.VariableName;
The visibility of the static variable is similar to the instance variable. However, you can declare the static variable as public so that it can be available for users of the class. You will learn more in detail in the static chapter.
Let’s take an example program based on the scope of static variables in Java programming.
Example 6:
package staticVariable;
public class StaticTest
{
// Declaration of static variable.
static int a = 20; // global or static scope
void m1()
{
int a = 30; // local scope
System.out.println("a: " +a);
System.out.println("a: " +StaticTest.a); // Accessing static variable using class name within instance method.
}
public static void main(String[] args)
{
StaticTest st = new StaticTest();
st.m1();
}
}
Output: a: 30 a: 20
Key Points to Remember:
1. Scope of a variable means simply the region of the program where a variable is accessible.
2. The scope of local variables always remains inside constructor, method, and block. They are made when the block is entered and destroyed when the block is exited. Therefore, it can not be accessible from outside the constructor, method, and block.
3. The scope of instance variables is within the class. We can access them from all the methods, constructors, and from the beginning of its program block to the end of program block in the class.
4. The scope of static variables is also within the class. All the methods, constructors, and blocks within class can access static variables by using the class name.