Variable Scope in Java:
Scope refers to the region or context within which a variable is accessible.
Block Scope:
- Block scope is the area within a pair of curly braces .
- Variables declared inside a block are accessible within that block only.
- Block scope is often associated with local variables.
scope.java
public void exampleMethod() {
int x = 10; // x is in block scope
{
int y = 20; // y is in block scope
}
// x is still accessible here, but y is not
}
Method Scope:
- Variables declared as method parameters or local variables inside a method have method scope.
- They are only accessible within the method where they are declared.
scope.java
public void exampleMethod(int a) {
int b = 20; // b has method scope
// Both a and b are accessible here
}
Class Scope (Instance Variables):
- Instance variables (fields) have class scope.
- They are declared within a class but outside of any method.
- Instance variables are accessible throughout the class and have the same lifetime as the class's object.
scope.java
public class MyClass {
int instanceVar = 30;
}
Class Scope (Static Variables):
- Static variables are shared among all instances of a class and also have class scope.
- They are declared as static within a class.
- Static variables exist for the entire lifetime of the program.
scope.java
public class MyClass {
static int staticVar = 40;
}
Global Scope:
- Java doesn't have true global variables (variables accessible everywhere in the program).
- The closest thing to a global scope in Java is a public static variable within a class.
scope.java
public class GlobalScopeExample {
public static int globalVar = 50;
}
Note : Scope defines the region or context within which a variable is accessible. Understanding the different scopes is crucial for writing clean and efficient code. Java does not have true global variables accessible everywhere in the program.