Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why can't I add constant of other class into a switch statement in java?

Why can’t I add constant of other class into a switch statement in java?

example: I have a class

public class Game {


    static class GameMode {
        public static final GameMode SURVIVAL = new GameMode();
        public static final GameMode ADVENTURE = new GameMode();
        public static final GameMode GOD = new GameMode();
    }

    GameMode CurrentMode = GameMode.GOD;

}

but when I define a switch statement, It give me an error:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    void OnGame(){
        switch (CurrentMode){
            case GameMode.GOD: // case expressions must be constant expressionsJava(536871065)
                System.out.println("Player On God Mode");
                break;
            case GameMode.SURVIVAL: // case expressions must be constant expressionsJava(536871065)
                System.out.println("Player On Survival Mode");
                break;
            case GameMode.ADVENTURE: // case expressions must be constant expressionsJava(536871065)
                System.out.println("Player On Adventure Mode");
                break;


        }
    }

That makes me confused. SURVIVAL, ADVENTURE and GOD mode are all constant, I add "final" in front of it, why can’t I use it in switch statement?

Here are some image:
enter image description here
enter image description here
enter image description here

>Solution :

According to Java Language Specification (JLS):

A case label has one or more case constants. Every case constant must be either a constant expression (§15.29) or the name of an enum constant (§8.9.1), or a compile-time error occurs.

Your case is obviously not an enum constant, so I guess you are trying to use a constant expression but your GameMode class does not qualify as a constant expression.

A constant expression is an expression denoting a value of primitive type or a String that does not complete abruptly and is composed using only the following

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading