Is the null type a reference type?

David Alayachew davidalayachew at gmail.com
Tue Jan 28 19:08:28 UTC 2025


Ty vm.

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

> Am 28.01.25 um 17:40 schrieb David Alayachew:
> > Isn't null a value and not a type?
>
> null is a value, and null type is a type,
>   see
> https://docs.oracle.com/javase/specs/jls/se23/html/jls-4.html#jls-4.1
>
> >
> > On Tue, Jan 28, 2025, 9:25 AM Stephan Herrmann <
> stephan.herrmann at berlin.de
> > <mailto: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/e392abba/attachment.htm>


More information about the compiler-dev mailing list