Variable scope in Java defines the region of a program where a variable can be accessed and used. Java follows lexical (static) scoping, which means the scope of a variable is determined at compile time based on where the variable is declared.
- Scope determines where a variable is accessible in a program.
- Variables declared inside a block { } are limited to that block only.
Scope
Scope determines the visibility and accessibility of variables inside a program.
- Variables declared inside a block { } are accessible only within that block.
- A variable cannot be used outside its defined scope.
Types of Variable Scope in Java
Java mainly provides the following types of variable scope:
1. Instance Variable Scope (Class Level Scope)
Instance variables are non-static variables declared inside a class but outside methods, constructors, or blocks. Each object of the class gets its own separate copy of these variables.
- Accessible throughout the class using object reference.
- Stored in heap memory.
- Created when an object is created and destroyed when the object is destroyed.
public class Test {
// All variables defined directly inside a class
// are member variables
int a;
private String b;
void method1() {....}
int method2() {....}
char c;
}
- We can declare class variables anywhere in the class, but outside methods.
- Access specified of member variables doesn't affect scope of them within a class.
- Member variables can be accessed outside a class.
Access Modifiers and Member Variable Scope
Modifier | Package | Subclass | World |
|---|---|---|---|
public | Yes | Yes | Yes |
protected | Yes | Yes | No |
Default (no modifier) | Yes | No | No |
private | No | No | No |
2. Static Variable Scope (Class Level Scope)
Static variables are declared using the static keyword. Only one copy of the variable exists and it is shared among all objects of the class.
- Accessed using class name.
- Memory is allocated only once.
// Using Static variables
import java.io.*;
class Test{
// static variable in Test class
static int var = 10;
}
class Geeks
{
public static void main (String[] args) {
// accessing the static variable
System.out.println("Static Variable : "+Test.var);
}
}
Output
Static Variable : 10
3. Local Variable Scope (Method Level Scope)
Local variables are declared inside methods, constructors, or blocks and can only be used within that method or block.
- Cannot be accessed outside the method.
- Created when the method starts and destroyed after execution ends.
public class Test {
void method1()
{
// Local variable (Method level scope)
int x;
}
}
Note: Local variables don't exist after method's execution is over.
4. Parameter Scope
Parameters are variables passed to methods or constructors. Their scope is limited to that specific method or constructor.
- Used to pass values to methods.
- Exist only during method execution.
class Test {
private int x;
public void setX(int x) {
this.x = x;
}
}
Example of Method and Parameter Scope:
public class Geeks
{
// Class Scope variable
static int x = 11;
// Instance Variable
private int y = 33;
// Parameter Scope (x)
public void testFunc(int x) {
// Method Scope (t)
Geeks t = new Geeks();
this.x = 22;
y = 44;
// Printing variables with different scopes
System.out.println("Geeks.x: " + Geeks.x);
System.out.println("t.x: " + t.x);
System.out.println("t.y: " + t.y);
System.out.println("y: " + y);
}
// Main Method
public static void main(String args[]) {
Geeks t = new Geeks();
t.testFunc(5);
}
}
Output
Geeks.x: 22 t.x: 22 t.y: 33 y: 44
5. Block Level Scope
A variable declared inside pair of brackets "{" and "}" in a method has scope within the brackets only.
- Cannot be used outside the block.
- Helps in temporary variable usage.
// Using Block Scope
public class Test
{
public static void main(String args[])
{
// Block Level Scope
{
// The variable x has scope within
// brackets
int x = 10;
System.out.println(x);
}
// Uncommenting below line would produce
// error since variable x is out of scope.
// System.out.println(x);
}
}
Output
10
Incorrect Usage of Local Variables
1. For Block Level Cases which are wrong
Let's look at tricky example of loop scope. Predict the output of following program. You may be surprised if you are regular C/C++ programmer.
class Test
{
public static void main(String args[])
{
// local variable declared
int a = 5;
// for loop variable declared
for (int a = 0; a < 5; a++)
{
System.out.println(a);
}
}
}
/*
Output:
6: error: variable a is already defined in method go(int)
for (int a = 0; a < 5; a++)
^
1 error
*/
// Java Program Implementing
// Block Level Variables
class Test
{
public static void main(String args[])
{
// Block Created
{
// variable inside block
int x = 5;
// Nested Block
{
// Variable inside nested block
int x = 10;
System.out.println(x);
}
}
}
}
/*
Output:
./Test.java:8: error: variable x is already defined in method main(String[])
int x = 10;
^
1 error
/*
Note: In C++, Program 1 will run. But in Java it is an error because in Java, the name of the variable of inner and outer loop must be different. A similar program in C++ works. See this.
2. Incorrect Way to use Local Variable - Block Scope
class Test
{
public static void main(String args[])
{
for (int x = 0; x < 4; x++)
{
System.out.println(x);
}
// Will produce error
System.out.println(x);
}
}
/*
Output:
11: error: cannot find symbol
System.out.println(x);
*/
// Correcting the error
class Test
{
public static void main(String args[])
{
int x;
for (x = 0; x < 4; x++) {
System.out.print(x + " ");
}
System.out.println(x);
}
}
Output:
0 1 2 3 4Java Program Demonstrating All Variable Scopes
public class Geeks {
// Instance Variable (belongs to each object)
private int instanceVar = 10;
// Static Variable (shared among all instances)
static int staticVar = 100;
// Constructor demonstrating parameter scope
public Geeks(int instanceVar) {
// Parameter Scope
// using 'this' to refer to instance variable
this.instanceVar = instanceVar;
}
// Method to demonstrate local, parameter, and block scope
public void showScopes(int paramVar) {
// Local Variable
// only accessible in this method
int localVar = 20;
System.out.println("Instance Variable: " + instanceVar);
System.out.println("Static Variable: " + staticVar);
System.out.println("Method Parameter: " + paramVar);
System.out.println("Local Variable: " + localVar);
// Block Scope (variable only accessible inside this block)
if (localVar > 10) {
int blockVar = 5;
System.out.println("Block Variable: " + blockVar);
}
// Uncommenting below line would cause an error: blockVar out of scope
// System.out.println(blockVar);
}
public static void main(String[] args) {
Geeks obj = new Geeks(50);
obj.showScopes(30);
}
}
Output
Instance Variable: 50 Static Variable: 100 Method Parameter: 30 Local Variable: 20 Block Variable: 5
Important Points about Variable Scope in Java
- Curly braces { } define the scope of variables.
- A variable can be accessed only within the block where it is declared.
- Local variables exist only inside methods.
- Instance variables can be accessed by all methods of the class.
- Static variables are shared among all objects of the class.
- Block variables are accessible only inside that block.
- Loop variables cannot be accessed outside the loop.
- this keyword is used to access class variables when names are same.