|
|
In the Java(TM) programming language, variable initialization depends on context. Consider the following:
int x;
Dog fido;
If x and fido are instance variables, they are automatically initialized to 0 and null, respectively. null is a special literal that can be assigned to any reference variable. In general, if there is no explicit initialization for an instance variable definition, Java automatically initializes the variable to a "zero-like" value, depending on the data type:
Consider the following program:
public class TestVariableInit {
public static void main(String[] args) {
TestClass tc = new TestClass();
System.out.println("tc.iStr = " + tc.iStr);
System.out.println("tc.i = " + tc.i);
}
}
class TestClass {
int i; // instance variable
String iStr; // instance variable
}
TestVariableInit produces the following output:
D:\>java TestVariableInit
tc.iStr = null
tc.i = 0
Several books state that this default initialization applies in all contexts, for example, with variables local to a method (local variables), and that in the case of uninitialized local variables the compiler will generate a warning, or possibly an error, depending on the Java environment. The fact is that, historically, several Java environments have performed no initialization for local variables and have given no warning or error, in which case the value is garbage. This situation can produce very hard to diagnose runtime errors. In the case of the Java Development Kit (JDK) from Sun Microsystems, the compiler reports uninitialized local variables as an error--at the point of their reference. Suppose we modify main() in TestVariableInit as follows:
public static void main(String[] args) {
TestClass tc = new TestClass();
String lStr; // local variable
int i; // local variable
System.out.println("tc.iStr = " + tc.iStr);
System.out.println("tc.i = " + tc.i);
System.out.println("lStr = " + lStr);
System.out.println("i = " + i);
}
Attempting to compile TestVariableInit produces the following output:
D:\>javac TestVariableInit.java
TestVariableInit.java:8: Variable lStr may not
have been initialized.
System.out.println("lStr = " + lStr);
^
TestVariableInit.java:9: Variable i may not
have been initialized.
System.out.println("i = " + i);
^
2 errors
In this type of situation, the idea that the Java environment guarantees a default value, but simply doesn't allow you to use it, is rather ridiculous. (If a tree falls in the forest, does it make a sound if no one is there to hear it?) Most programmers would agree that instance variables should be initialized for the sake of readability, and local variables must be initialized for the sake of programmers' sanity everywhere, that is, for wherever and with whatever environment the source code might be compiled today, tomorrow, and after no one remembers who wrote the code. copyright 1996-2000 Magelang Institute dba jGuru |
|