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?

2 Answers

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;

    ...

}

0 votes
ago by (1.8k points)

Basically this is an error that generally occurs when java is not able to verify the constant nature of expression even if it appears constant in your code.Switch statement in java requires that case labels are compile time constants

For Foo.BAR, Foo.BAZ, and Foo.BAM to be used in a switch statement, they must be assigned their values directly. Here’s how you can modify your class:

java

public abstract class Foo {

    public static final int BAR = 1;

    public static final int BAZ = 2;

    public static final int BAM = 3;

}

With the constants explicitly assigned values, you can use them in your switch statement without any errors:

java

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";

    }

}

If BAR, BAZ, and BAM need to be computed or set in some non-constant way, they won’t qualify for use in a switch statement. In that case, an if-else construct would be more appropriate.

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...