What are the different scopes of a variable in Java, from a local variable in a block up to a static field?
Java has three main places where a variable can live, and each one has a different reach.
A local variable is declared inside a block of code, which is usually the body of a method. It can only be used between the point where you declare it and the end of the block. When the block finishes, the variable is gone, and every call to the method gets its own fresh copy of it.
An instance field is declared at the top level of a class without the word static. There is one copy of it for every object of that class, and it lives for as long as the object lives. It is the state that makes an object meaningful.
A static field is declared at the top level of a class with the word static. There is exactly one copy of it for the whole class, no matter how many objects exist, and it lives for as long as the class is loaded.
A method parameter is a local variable as well. It lives inside the method, and it gets a fresh copy on every call.
public class ScopeDemo {
private int instanceField = 1; // one copy for every object
private static int staticField = 2; // one copy for the whole class
public void method(int parameter) {
int local = 3; // a fresh copy on every call
System.out.println("parameter : " + parameter);
System.out.println("local : " + local);
System.out.println("instance : " + instanceField);
System.out.println("static : " + staticField);
}
}
The next question in this topic looks at why one of those places cannot be reached from a static method.