Table of contents
1.
Introduction
2.
Types of Variable Scope in Java
3.
Local Variables
3.1.
Definition and Characteristics
3.2.
Syntax
3.3.
Example with Code
3.4.
Java
4.
Instance Variables
4.1.
Definition and Characteristics
4.2.
Syntax
4.3.
Example with Code
4.4.
Java
5.
Class/Static Variables
5.1.
Definition and Characteristics
5.2.
Syntax
5.3.
Example with Code
5.4.
Java
6.
Block Scope
6.1.
Definition and Characteristics
6.2.
Syntax
6.3.
Example with Code
6.4.
Java
7.
Variable Shadowing
7.1.
What is Variable Shadowing? 
7.2.
Examples and Explanation
7.3.
Java
7.4.
Best Practices for Variable Scope
8.
Frequently Asked Questions
8.1.
What is the difference between instance variables and static variables?
8.2.
Can local variables be accessed outside their method?
8.3.
What happens if two variables have the same name in different scopes?
8.4.
How can I avoid variable shadowing?
9.
Conclusion
Last Updated: Jul 20, 2024
Easy

Scope of Variables in Java

Author Rinki Deka
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

In Java, the scope of a variable defines where the variable can be accessed within the code. Understanding variable scope is crucial for writing effective and error-free code. It helps in managing memory efficiently and avoiding errors such as variable shadowing. 

Scope of Variables in Java

This article will explore the different types of variable scopes in Java, with examples to illustrate each type.

Types of Variable Scope in Java

Java variables can have different scopes based on where they are declared. The main types of variable scope in Java are:

  1. Local Scope
     
  2. Instance Scope
     
  3. Class/Static Scope
     
  4. Block Scope

Local Variables

Definition and Characteristics

Local variables are declared within a method or a constructor. They are created when the method or constructor is called and destroyed once the method or constructor finishes executing. Local variables are not accessible outside the method or constructor.

Syntax

public class Main {
    public void exampleMethod() {
        int localVar = 10; // local variable
        System.out.println(localVar);
    }
}

Example with Code

  • Java

Java

public class Main {

   public void printLocalVariable() {

       int localVar = 25;

       System.out.println("Local Variable: " + localVar);

   }

   public static void main(String[] args) {

       Main obj = new Main();

       obj.printLocalVariable();

   }

}
You can also try this code with Online Java Compiler
Run Code


Output

Local Variable: 25

Instance Variables

Definition and Characteristics

Instance variables are declared within a class but outside any method, constructor, or block. They are created when an object of the class is instantiated and destroyed when the object is destroyed. Instance variables hold values that are unique to each instance of the class.

Syntax

public class Main {
    int instanceVar = 30; // instance variable
}

Example with Code

  • Java

Java

public class Main {

   int instanceVar = 50;

   public void printInstanceVariable() {

       System.out.println("Instance Variable: " + instanceVar);

   }

   public static void main(String[] args) {

       Main obj1 = new Main();

       Main obj2 = new Main();

       obj1.instanceVar = 75;

       obj2.instanceVar = 100;       

       obj1.printInstanceVariable();

       obj2.printInstanceVariable();

   }

}
You can also try this code with Online Java Compiler
Run Code


Output

Instance Variable: 75
Instance Variable: 100

Class/Static Variables

Definition and Characteristics

Class variables, also known as static variables, are declared with the static keyword within a class but outside any method, constructor, or block. They are shared among all instances of the class. Static variables are created when the program starts and destroyed when the program stops.

Syntax

public class Main {
    static int staticVar = 40; // static variable
}

Example with Code

  • Java

Java

public class Main {

   static int staticVar = 60;

   public void printStaticVariable() {

       System.out.println("Static Variable: " + staticVar);

   }

   public static void main(String[] args) {

       Main obj1 = new Main();

       Main obj2 = new Main();

       obj1.staticVar = 80;      

       obj1.printStaticVariable();

       obj2.printStaticVariable();

   }

}
You can also try this code with Online Java Compiler
Run Code


Output

Static Variable: 80
Static Variable: 80

Block Scope

Definition and Characteristics

Block scope variables are declared within a block of code such as loops, if statements, or any block enclosed within curly braces {}. They are accessible only within that block and are destroyed once the block is exited.

Syntax

public class Main {
    public void exampleMethod() {
        if (true) {
            int blockVar = 20; // block variable
            System.out.println(blockVar);
        }
        // blockVar is not accessible here
    }
}

Example with Code

  • Java

Java

public class Main {

   public void printBlockVariable() {

       for (int i = 0; i < 5; i++) {

           int blockVar = i * 2;

           System.out.println("Block Variable: " + blockVar);

       }

       // blockVar is not accessible here

   }

   public static void main(String[] args) {

       Main obj = new Main();

       obj.printBlockVariable();

   }

}
You can also try this code with Online Java Compiler
Run Code


Output

 // Block Variable: 0
// Block Variable: 2
// Block Variable: 4
// Block Variable: 6
// Block Variable: 8

Variable Shadowing

What is Variable Shadowing? 

Variable shadowing occurs when a variable declared within a certain scope has the same name as a variable declared in an outer scope. This can lead to confusion and errors in the code.

Examples and Explanation

  • Java

Java

public class Main {

   int var = 100; // instance variable

   public void printVariable() {

       int var = 200; // local variable shadowing instance variable

       System.out.println("Local Variable: " + var);

   }

   public static void main(String[] args) {

       Main obj = new Main();

       obj.printVariable();

       System.out.println("Instance Variable: " + obj.var);

   }

}
You can also try this code with Online Java Compiler
Run Code


Output

Local Variable: 200
Instance Variable: 100


In the above example, the local variable var in the printVariable method shadows the instance variable var.

Best Practices for Variable Scope

  • Minimize Variable Scope: Declare variables in the smallest scope possible to reduce complexity and potential errors.
     
  • Use Descriptive Names: Give variables meaningful names to avoid confusion and improve code readability.
     
  • Avoid Shadowing: Avoid using the same name for variables in different scopes to prevent shadowing.

Frequently Asked Questions

What is the difference between instance variables and static variables?

Instance variables are unique to each object instance, while static variables are shared among all instances of a class.

Can local variables be accessed outside their method?

No, local variables are only accessible within the method or block where they are declared.

What happens if two variables have the same name in different scopes?

The variable in the innermost scope will shadow the variable in the outer scope.

How can I avoid variable shadowing?

Use unique and descriptive names for variables, and avoid reusing names within nested scopes.

Conclusion

Understanding the scope of variables in Java is essential for writing efficient and error-free code. By knowing the differences between local, instance, static, and block scope, you can manage memory better and avoid common pitfalls such as variable shadowing. Remember to follow best practices for variable scope to keep your code clean and maintainable.

You can also practice coding questions commonly asked in interviews on Coding Ninjas Code360

Also, check out some of the Guided Paths on topics such as Data Structure and AlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Live masterclass