Initializing Local Reference Variables
Local reference variables are bound by the same initialization rules as local variables of primitive data types.
Example 3.3 Flagging Uninitialized Local Reference Variables
public class VerySmartClass {
public static void main(String[] args) {
String importantMessage; // Local reference variable
System.out.println(“The message length is: ” +
importantMessage.length()); // Compile-time error!
}
}
In Example 3.3, the compiler complains that the local variable importantMessage used in the println statement may not be initialized. If the variable important-Message is set to the value null, the program will compile. However, a runtime error (NullPointerException) will occur when the code is executed because the variable importantMessage will not denote any object. The golden rule is to ensure that a reference variable, whether local or not, is assigned a reference value denoting an object before it is used—that is, to ensure that it does not have the value null.
The program compiles and runs if we replace the declaration with the following declaration of the local variable, which creates a string literal and assigns its reference value to the local reference variable importantMessage:
String importantMessage = “Initialize before use!”;
Arrays and their default values are discussed in §3.9, p. 119.
Lifetime of Variables
The lifetime of a variable—that is, the time a variable is accessible during execution—is determined by the context in which it is declared. The lifetime of a variable, which is also called its scope, is discussed in more detail in §6.6, p. 352. We distinguish among the lifetime of variables in the following three contexts:
- Instance variables: members of a class, which are created for each object of the class. In other words, every object of the class will have its own copies of these variables, which are local to the object. The values of these variables at any given time constitute the state of the object. Instance variables exist as long as the object they belong to is in use at runtime.
- Static variables: members of a class, but which are not created for any specific object of the class, and therefore, belong only to the class. They are created when the class is loaded at runtime and exist as long as the class is available at runtime.
- Local variables (also called method automatic variables): declared in methods, constructors, and blocks, and created for each execution of the method, constructor, or block. After the execution of the method, constructor, or block completes, local variables are no longer accessible.