January 5, 2010

Default initialization in Java

In Java, class variables get initialized to default values. This code...

public class Test {
private static String _string;
private static byte _byte;
private static short _short;
private static int _int;
private static long _long;
private static float _float;
private static double _double;
private static boolean _boolean;
private static char _char;

public static void main(String[] args) {
System.out.println("str " + _string);
System.out.println("byt " + _byte);
System.out.println("sht " + _short);
System.out.println("int " + _int);
System.out.println("lng " + _long);
System.out.println("flt " + _float);
System.out.println("dbl " + _double);
System.out.println("bln " + _boolean);
System.out.println("chr " + _char);
}
}


...produces this output...

str null
byt 0
sht 0
int 0
lng 0
flt 0.0
dbl 0.0
bln false
chr [the non-printable character U+0000]

Unlike class variables, method-local variables are NOT automatically initialized. This code will produce a compile-time error ("the local variable anotherInt may not have been initialized"):

int anotherInt;
System.out.println(anotherInt);


On the other hand, the compiler won't catch non-initialized class objects; this code, after the earlier snippet, compiles just fine but will cause a NullPointerException at runtime:

if ("impossible".equals(_string)) {
int x = 5;
}

No comments:

Post a Comment