I was experimenting with enum, and I found that the following compiles and runs fine on Eclipse (Build id: 20090920-1017, not sure exact compiler version):
public class SwitchingOnAnull {
enum X { ,; }
public static void main(String[] args) {
X x = null;
switch(x) {
default: System.out.println("Hello world!");
}
}
}
When compiled and run with Eclipse, this prints "Hello world!" and exits normally.
With the javac compiler, this throws a NullPointerException as expected.
So is there a bug in Eclipse Java compiler?
This is a bug. Here’s the specified behavior for a
switchstatement according to the Java Language Specification, 3rd Edition:JLS 14.11 The
switchStatementApparently the bug in Eclipse has nothing to do with
defaultcase orenumat all.The above code compiles and runs “fine” on (at least some version of) Eclipse. Each individual
switchthrows aNullPointerExceptionwhen compiled withjavac, which is exactly as the specification mandates.The cause
Here’s
javap -c SwitchingOnAnullwhen compiled under Eclipse:It seems that the Eclipse compiler gets rid of the entire
switchconstructs entirely. Unfortunately this optimization breaks the language specification.The official words
The bug has been filed and assigned for fix.
See also
nullexpression doesn’t always throwNullPointerException