5.2 Scope and Lifetime
Scope decides where a name is visible. A variable declared inside a method or block is local.
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
// i cannot be used hereMethod parameters are local variables too. When a method is called, argument values are copied into parameters, so changing a parameter does not automatically change the caller's variable.
A classic example is swap(): it tries to exchange two variables inside a method, but fails for primitive int values.
static void swap(int a, int b) {
int temp = a;
a = b;
b = temp;
}
public static void main(String[] args) {
int x = 3;
int y = 8;
swap(x, y);
System.out.println(x + " " + y);
}Output:
3 8swap() only exchanges its own local copies a and b; x and y in main never change. To really update caller-visible data in Java, you usually return a value, update an array/object that was passed in, or design a small object to hold the result.
A field declared in a class can be accessed by methods in that class. If the field is static, it belongs to the class itself. Long-lived shared state can make data changes harder to trace, so prefer local variables and parameters first.
Java does not support C-style static local variables inside a method. When you need a value to persist across method calls, use a field.