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){It will fail to compile with this error:
java.util.Date d;
System.out.println(d);
}
variable d might not have been initializedHowever, the following will compile and run successfully:
System.out.println(d);
1 error
public static void main(String[] args){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:
java.util.Date d;
}
public static void main(String[] args){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.
java.util.Date d;
//do more work
d = new java.util.Date();
System.out.println(d);
}
Tags: