Is the null type a reference type?

David Alayachew davidalayachew at gmail.com
Tue Jan 28 16:40:36 UTC 2025


Isn't null a value and not a type?

On Tue, Jan 28, 2025, 9:25 AM Stephan Herrmann <stephan.herrmann at berlin.de>
wrote:

> 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
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/compiler-dev/attachments/20250128/04bc1e33/attachment-0001.htm>


More information about the compiler-dev mailing list