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 defines the area of the program where you can access or modify its value. The scope of variables determines its accessibility to 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.

Types of Variable Scope in Java


There are four main types of variable scope in Java:

  • Local Scope (Method Scope)
  • Instance scope (Class Level Scope, Non-static)
  • Class Scope (Static)
  • Block Scope

Let’s discuss each of them in detail with examples.

Local Scope (Method Scope) in Java


Local scope in Java defines the region or area of a method, constructor, or any block of code in a program. In this scope, we define local variables. A local variable is a variable that is declared inside methods, constructors, or blocks. You can use it only within the part of the program where it is defined.

Key Points About Local Scope

1. Accessibility:

  • In local scope, local variables are visible and accessible only within the method, constructor, or block of code where they are declared.
  • When you create a local variable inside a method or any block of code, its scope remains limited to that block only.
  • Local variables are not accessible from outside that scope, not even by other methods within the same class.

2. Lifetime:

  • As soon as the program execution exits from the method or block, the scope of the local variable ends, meaning the variable is destroyed. Therefore, you cannot access or modify it from outside the method, constructor, or block.
  • You cannot also change its value from outside of any block.

3. Initialization:

  • Unlike instance or static variables, local variables do not have a default value.
  • You must explicitly initialize a local variable before using it.
  • If you try to use it without initialization, the compiler will generate a compile-time error.

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: Accessing Local Variable Outside the Method

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 trying to access 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 inside the method m1(). Since x is a local variable, we cannot access it from the outside the method block. Hence, the program generates a compile-time error.

Example 2: Scope of Local Variables Inside Constructor and Methods

public class School 
{ 
// Declare instance variable. 
   public String name = "John"; 

// Declaration of constructor. 
   School()
   { 
      int id = 1234; // local variable, accessible only within this constructor block.
      System.out.println("Id of Student: " +id); 
   } 
// Declaration of user-defined method. 
   public void mySchool()
   { 
  // Declaration of local variable. 
     String schoolName = "RSVM"; // accessible only 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 their method, constructor, or block.
    System.out.println("Name of School: " +schoolName) // Compile-time error
  } 
  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 above example, the variable schoolName is declared inside the method mySchool(), so its scope is limited to that method only. If we try to access it from another method like mySchool2(), it will cause a compile-time error because local variables are not visible outside their defining block.

Let’s take one more example to understand the scope of local variable more clearly in Java.

Example 3: Trying to Access Local Variables Outside Their Scope

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(); 

   // Trying to access the local variables from outside the method or constructor. 
      System.out.println("Name of School: " +schoolName); // compilation error. 
      System.out.println("Id of Student: " +id); // compilation error. 
   } 
}

In this example, the local variables id (declared in the constructor) and schoolName (declared in the method) cannot be accessed from the main() method because their scope is limited to the block in which they were declared.

Instance Scope in Java


Instance scope in Java defines the region or area within a class, but outside of any method, constructor, or block. In this scope, we define instance variables.

An instance variable is a variable that is declared within a class but outside any method, constructor, or block. It is associated with an object of the class, and each object has its own separate copy of the instance variable.

Key Points About Instance Scope

1. Accessibility:

  • When you define an instance variable inside a class (but outside any method, constructor, or block), its scope extends throughout the entire class. Therefore, it is visible and accessible to all methods, constructors, and blocks from the beginning to the end of the class definition.
  • In other words, all the methods, constructors, and blocks inside the class can access instance variables directly.
  • It is generally recommended to declare instance variables as private to achieve encapsulation. However, you can control their visibility to subclasses or other classes using access modifiers, such as public, protected, or private.
  • Each object of a class has its own copy of the instance variable, meaning that changes made by one object do not affect the values in another object.

2. Lifetime:

  • An instance variable is created in memory when you create an object of a class and destroyed when the object is destroyed. In simple words, it exists as long as the object remains in memory.

3. Initialization:

  • Instance variables are automatically initialized with their default values if you do not explicitly assign a value.
  • For example:
    • Numeric types (int, float, double) → 0
    • boolean → false
    • Object references → null

Let’s take some example programs based on the scope of instance variables in Java.

Example 4: Scope of Instance and Local Variables

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 method declaration.
   void addition()
   { // Block 3. 
     int x = 100; 
     int add = a + b + x; // Variables a and b declared in block 1 are accessible here. 
     System.out.println("Sum: " +add); 
   } 
   void subtraction()
   { // Block 4. 
      int sub = a + b + c; // Variable c is not accessible here 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

In this example program,

  • The variables a and b declared in block 1 are instance variables , so they are accessible to all methods or blocks inside the class.
  • The variable c is a local variable declared inside the constructor (block 2), so it is only accessible within that block.
  • Attempting to use c in the subtraction() method causes a compile-time error because c is out of scope there.

Hence, the variables a and b are visible to all blocks, but variable c is limited to the constructor block only.

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.

Example 5: Local Variable Hiding Instance Variable

Let’s take an example where we will declare the instance and local variables with the same name and definition.

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 this example program,

  • The instance variable num has the value 20.
  • Inside the m1() method, a local variable num is declared with the value 30.

Here, the local variable hides (shadows) the instance variable within the method’s scope. Therefore, when we will call m1() method from the main() method, the output will display num equal to 20, even though there is also a num instance variable that equals to 30.

To access the instance variable hidden by the local one, we use the this keyword — this.num refers to the instance variable with value 20.

Static Scope (Class Scope) in Java


Static scope in Java defines the region within a class where variables are declared using the static keyword. In this scope, we define static variables. A static variable is a variable that is declared inside a class using the static keyword, but outside any method, constructor, or block.

Static variables are also called class variables because they are associated with the class itself rather than with individual objects. This means that their values are shared among all instances of the class. Any change made to a static variable is reflected across all objects of that class.

Key Points About Static Scope

1. Accessibility:

  • Static variables belong to the class itself, not to any specific object.
  • A single copy of a static variable is shared among all instances of the class.
  • All the methods, constructors, and blocks inside the class can access static variables using the class name.

2. Lifetime:

  • Static variables are created when the class is loaded in the memory and remain in memory until the program terminates.

3. Initialization:

  • Static variables are automatically initialized with their default values if you do not explicitly assign a value.
  • You can also explicitly initialize them during declaration or within a static block.

Let’s take an example program based on the scope of static variables in Java.

Example 6: Accessing Static Variables

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);
   // Accessing static variable using class name within instance method.  
      System.out.println("a: " +StaticTest.a); 
   }
   public static void main(String[] args) 
   { 
     StaticTest st = new StaticTest(); 
     st.m1(); 
   } 
}

Output:

a: 30 
a: 20

Block Scope in Java


A block scope defines the region inside a pair of curly braces { } such as loops, conditional statements, or standalone blocks. In this scope, we generally define local variables.

Key Points About Block Scope

1. Accessibility:

  • Since variable defined inside a block scope are local variables, they are accessible only within that block and any nested blocks.
  • They cannot be accessed from outside the block where they are declared.

2. Lifetime:

  • Variables defined inside block scope exist only while the program code is executing within that block.
  • Once the execution exits the block, the variables are destroyed, and their memory is released.

Example 7: Block Scope

public class BlockScopeExample {
public static void main(String[] args) {
    int x = 10;  // variable in main method scope
    System.out.println("Value of x: " + x);

 // Start of block
    {
       int y = 20;  // variable in block scope
       System.out.println("Value of y inside block: " + y);
       System.out.println("Accessing x inside block: " + x); // accessible
    }
    // End of block

    // Trying to access y outside the block
    // System.out.println("Value of y outside block: " + y); // Compile-time error: y cannot be resolved
   }
}

Output:

Value of x: 10
Value of y inside block: 20
Accessing x inside block: 10

In this example,

  • The variable x is declared in the main method scope, so it is accessible throughout the main() method, including inside the inner block.
  • The variable y is declared inside the block { }, so its scope is limited to that block only.
  • When the block ends, the variable y is destroyed and cannot be accessed outside the block.
  • If you try to print y outside the block, Java will throw a compile-time error.

Java Scope Hierarchy


Scope of a variable simply means the region or part of a program where that variable is accessible and usable. The following table summarizes the scope of variables in Java:

Scope TypeWhere DeclaredAccessible WithinLifetimeMemory Area
LocalInside methods, constructors, or blocksOnly within the same blockUntil block endsStack
InstanceInside class, outside methodsAll non-static methods of the classAs long as object existsHeap
StaticstaticAccessible using class nameUntil program endsMethod Area
BlockInside { } (loops, if, etc.)Within the same blockUntil block endsStack

 

DEEPAK GUPTA

DEEPAK GUPTA

Deepak Gupta is the Founder of Scientech Easy, a Full Stack Developer, and a passionate coding educator with 8+ years of professional experience in Java, Python, web development, and core computer science subjects. With strong expertise in full-stack development, he provides hands-on training in programming languages and in-demand technologies at the Scientech Easy Institute, Dhanbad.

He regularly publishes in-depth tutorials, practical coding examples, and high-quality learning resources for both beginners and working professionals. Every article is carefully researched, technically reviewed, and regularly updated to ensure accuracy, clarity, and real-world relevance, helping learners build job-ready skills with confidence.