In Java, class instance variables and static variables have default values: null
for all object types, false
for boolean primitive and 0 for numeric primitives. But local variables inside a method have no defaults.
Consider the following code snippet:
public static void main(String[] args){
java.util.Date d;
System.out.println(d);
}
It will fail to compile with this error:variable d might not have been initialized
System.out.println(d);
1 error
However, the following will compile and run successfully:public static void main(String[] args){
java.util.Date d;
}
Because the rule is that all local variables must be initialized before they are first read. So it's perfectly OK to first declare a local variable without initializing it, initialize it later, and then use it:public static void main(String[] args){
java.util.Date d;
//do more work
d = new java.util.Date();
System.out.println(d);
}
It may be an old habit from languages like C, where you need to declare all local variables at the beginning of a code block. But in Java with this rule in place, it's best to defer declaring local variables till needed.
No comments:
Post a Comment