Yesterday I read an article of an interview with Joshua Bloch about Java. In the interview he talked about where Java was heading and some of its quirks. Here’s an example of a quirk he gave in the interview:
public class Unbelievable {
static Integer i;
public static void main(String[] args) {
if (i == 42)
System.out.println("Unbelievable");
}
}
Fairly innocuous bit of code … so what does it do? Well if you run it you get a NullPointerException, which is no surprise as the variable hasn’t been initialized. What is surprising is why the compiler didn’t pick this up at compile time! For example, if I modify the code to the example below, it doesn’t compile because the variable has not been initialized:
public class Unbelievable {
public static void main(String[] args) {
Integer i;
if (i == 42)
System.out.println("Unbelievable");
}
}
Any Java experts out there care to explain this one to me? I compiled the above examples using Java 1.5 on the Mac.