In Java, variables have different scopes depending on where they are declared within a program. Understanding variable scope is important for proper variable usage and avoiding errors.
In this article, we will explore the different scopes of variables in Java and provide examples to illustrate each scope.
Member Variables (Class Level Scope) Member variables are declared inside a class but outside any method. These variables have class-level scope and can be accessed by any method within the class.
Here's an example of a class with member variables:
csharppublic class MyClass {
int x; // member variable
String str; // member variable
public void myMethod() {
// code that uses x and str
}
}
- public: can be accessed by any class in the program
- protected: can be accessed by classes in the same package and subclasses of the class
- default (no modifier): can be accessed by classes in the same package
- private: can only be accessed by the class itself
Local Variables (Method Level Scope) Local variables are declared inside a method and have method-level scope. These variables can only be accessed within the method and do not exist outside the method.
Here's an example of a method with local variables:
javapublic class MyClass {
public void myMethod() {
int x = 5; // local variable
String str = "hello"; // local variable
// code that uses x and str
}
}
Note that local variables are destroyed when the method is exited.
Loop Variables (Block Scope) Loop variables are declared inside a loop block and have block-level scope. These variables can only be accessed within the block and do not exist outside the block.
Here's an example of a loop with a loop variable:
csharppublic class MyClass {
public void myMethod() {
for (int i = 0; i < 5; i++) {
// code that uses i
}
// i is not accessible here
}
}
Note that loop variables are destroyed when the block is exited.
Shadowing Shadowing occurs when a variable in an inner scope has the same name as a variable in an outer scope. In this case, the inner variable "shadows" the outer variable and makes it inaccessible within the inner scope.
Here's an example of shadowing:
csharppublic class MyClass {
int x = 5; // outer variable
public void myMethod() {
int x = 10; // inner variable
// code that uses x (refers to the inner variable)
}
}
In this example, the inner variable "x" shadows the outer variable "x".
Conclusion In Java, variables have different scopes depending on where they are declared. Member variables have class-level scope, local variables have method-level scope, and loop variables have block-level scope. Shadowing can occur when a variable in an inner scope has the same name as a variable in an outer scope. Understanding variable scope is important for proper variable usage and avoiding errors.