Fully qualified enum constants in switch labels since Java 21

Turkhan Badalov badalov.turxan at gmail.com
Wed Nov 6 16:59:44 UTC 2024


The JLS says
<https://docs.oracle.com/javase/specs/jls/se21/html/jls-14.html#jls-14.11.1>
"Every case constant must be either a constant expression (§15.29), or the
name of an enum constant (§8.9.1), otherwise a compile-time error occurs."
which I believe explains why using anything besides simple name of an enum
constant in switch labels leads to compilation error. In fact, this was
very obvious prior to java 14 where SwitchLabel expected EnumConstantName
which itself was just an Identifier:
https://docs.oracle.com/javase/specs/jls/se13/preview/switch-expressions.html#jep354-14.11.1
. Today, even though SwitchLabel expects a ConditionalExpression which many
layers down is ExpressionName, the restriction remained until Java 21.

Since Java 21 using fully-qualified enum names in switch labels compiles
and works fine. Yet I can't find anything in JLS which would result in this
change. Is that a bug or intended to be so? Will appreciate if someone can
point me to the part of JLS that resulted in this change. Attaching a
minimal reproducible code which fails on Java versions prior to 21 and
compiles since 21.


package org.example;

enum Demo {
    ONE, TWO
}

public class Main {
    public static void main(String[] args) {
        final Demo input = Demo.ONE;
        switch(input) {
            case Demo.ONE: {}
            case org.example.Demo.TWO: {}
        }
    }
}

Regards,
Turkhan
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/amber-dev/attachments/20241106/6623d236/attachment.htm>


More information about the amber-dev mailing list