Understanding Variable Scope in Java
Types of Scope
In Java, there are four types of scope: local, instance, class, and method parameters. Each type of scope has its own rules and implications for how variables are declared and used.
A variable declared outside a block can be used inside the block, but a variable declared inside a block cannot be used outside the block. For example:
Recommended by LinkedIn
public class Main {
public static void main(String[] args) {
int x = 10; // declared outside the block
{ // this is a block
int y = 20; // declared inside the block
System.out.println(x); // prints 10
System.out.println(y); // prints 20
}
System.out.println(x); // prints 10
// System.out.println(y); // error: y cannot be resolved
}
}
A variable declared outside a block cannot be redeclared inside the block with the same name. For example:
public class Main {
public static void main(String[] args) {
int x = 10; // declared outside the block
{ // this is a block
// int x = 20; // error: duplicate local variable x
System.out.println(x); // prints 10
}
System.out.println(x); // prints 10
}
}
A variable declared inside a block can be redeclared outside the block with the same name, as long as they are in different scopes. For example:
public class Main {
public static void main(String[] args) {
{ // this is a block
int x = 10; // declared inside the block
System.out.println(x); // prints 10
}
int x = 20; // declared outside the block
System.out.println(x); // prints 20
}
}