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?
Definitly. If we look at the chapter 14.11 of the java language specification, it clearly states (under 'discussion'):
This is a bug. Here's the specified behavior for a
switch
statement according to the Java Language Specification, 3rd Edition:JLS 14.11 The
switch
StatementApparently the bug in Eclipse has nothing to do with
default
case orenum
at all.The above code compiles and runs "fine" on (at least some version of) Eclipse. Each individual
switch
throws aNullPointerException
when compiled withjavac
, which is exactly as the specification mandates.The cause
Here's
javap -c SwitchingOnAnull
when compiled under Eclipse:It seems that the Eclipse compiler gets rid of the entire
switch
constructs entirely. Unfortunately this optimization breaks the language specification.The official words
The bug has been filed and assigned for fix.
See also
null
expression doesn't always throwNullPointerException
Yep. According to the JLS it's a bug: