Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (10.2k points)

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?

1 Answer

0 votes
by (46k points)

You get Constant expression required because you left the values off your constants. Try:

public abstract class Foo {

    ...

    public static final int BAR=0;

    public static final int BAZ=1;

    public static final int BAM=2;

    ...

}

Browse Categories

...