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:
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?
>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…


