Is the null type a reference type?

Stephan Herrmann stephan.herrmann at berlin.de
Tue Jan 28 14:24:59 UTC 2025


Assume this (nonsense) program, which is accepted by javac and ecj:

public class X {
	public static void main(String[] args) {
		switch (null) {
			case null -> System.out.println("Null");
			default-> System.out.println("Default");
		}
	}
}

14.1.1 Switch Blocks requires (T is the type of the selector expression):
* If a null literal is associated with the switch block, then T is a reference type.

In our case the selector expression has the null type, which can be assigned to 
any reference type, but it doesn't seem to be a reference type itself.

 From this I would conclude that the program is illegal.


Next, lets remove the default case from the same program. Now compilers 
complain, here's how javac puts it:

X.java:3: error: the switch statement does not cover all possible input values
                 switch (null) {
                 ^
1 error

In previous discussions I learned that requiring a default label may be 
justified by requirements of future changes, but here for this reasoning to hold 
the null type would need to acquire new values, which seems very unlikely :). 
So, if the initial program would get the blessing from JLS, then also this case 
(without default) deserves a second look.

thanks,
Stephan


More information about the compiler-dev mailing list