Java Scope
Scope describes where in your code a variable can be seen and used. Understanding scope helps you avoid errors like 'cannot find symbol' and keeps different parts of your program from interfering with each other.
What scope means
A variable exists only within the region where it is declared. Outside that region, the variable is invisible and cannot be used. In Java, scope is usually defined by curly braces: a variable declared inside a pair of braces lives only until the closing brace.
Method scope
A variable declared inside a method is called a local variable. It can be used anywhere after its declaration within that method, but it does not exist in any other method. Each method has its own private set of local variables.
A local variable stays local
public class Main {
static void showMessage() {
String message = "Inside the method";
System.out.println(message);
}
public static void main(String[] args) {
showMessage();
// System.out.println(message); // ERROR: message is not visible here
}
}
// Output:
// Inside the methodThe variable message belongs to showMessage. If you uncomment the line in main, the program will not compile, because main has no idea that message exists.
Block scope
Scope can be even narrower than a whole method. Any block of curly braces, such as the body of an if statement or a for loop, creates its own scope. A variable declared inside that block disappears when the block ends.
A variable declared inside a loop
public class Main {
public static void main(String[] args) {
for (int i = 1; i <= 3; i++) {
int doubled = i * 2;
System.out.println(doubled);
}
// System.out.println(i); // ERROR: i only exists in the loop
// System.out.println(doubled); // ERROR: doubled only exists in the loop body
}
}
// Output:
// 2
// 4
// 6Nested blocks can see outer variables
Inner blocks can read outer variables
public class Main {
public static void main(String[] args) {
int total = 0; // visible in main and inside the loop
for (int i = 1; i <= 5; i++) {
total = total + i; // the loop can use total
}
System.out.println(total); // total is still visible here
}
}
// Output:
// 15Exercise: Java Scope
What is the scope of a variable declared inside a method's body?