Ask a Question
Ask Question Login
Corporate Training
  1. Community
  2. Java
  3. Question
Java

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

Asked by Colin Payne Mar 9, 2021 3.6K views 1 answer
Share

About this question

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?

Your answer

1 Answer

More Java discussions

Learn & Explore

Free tutorials and interview questions from industry experts — learn the skill, then get ready to prove it.

Latest Java Blogs

Guides, tips and career advice on Java from JanBask experts.