Java switch statement: Constant expression required, but is it constant?

1.4K    Asked by ColinPayne in Java , Asked on Mar 9, 2021

So, I am working on this class that has a few static constants:

public abstract class Foo {

    ...

    public static final int BAR;

    public static final int BAZ;

    public static final int BAM;

    ...

}

Then, I would like a way to get a relevant string based on the constant:

public static String lookup(int constant) {

    switch (constant) {

        case Foo.BAR: return "bar";

        case Foo.BAZ: return "baz";

        case Foo.BAM: return "bam";

        default: return "unknown";

    }

}

However, when I compile, I get a constant expression required error on each of the 3 case labels.

I understand that the compiler needs the expression to be known at compile-time to compile a switch, but why isn't Foo.BA_ constant?

Answered by Andrew Jenkins

Your Answer

Interviews

Parent Categories