I tried the following code:
String str = "Str1";
switch(str) {
case Constants.First_String : System.out.println("First String");
break;
case Constants.Second_String : System.out.println("Second String");
break;
default : System.out.println("Default String");
}
And my Constants
class is,
public class Constants {
public static String First_String = "Str1";
public static String Second_String = "Str2";
public static String Third_String = "Str3";
}
And I got a compilation error as,
Exception in thread "main" java.lang.Error: Unresolved compilation problems: case expressions must be constant expressions
But when I tried with following code,
switch(str){
case "Str1" : System.out.println("First String");
break;
case "Str2" : System.out.println("Second String");
break;
default : System.out.println("Default String");
}
No Compilation errors, and prints the output as,
First String
My question is, why in the first case compliation error occurs. And how can I resolve it.
final
. Sopublic static String First_String = "Str1";
becomespublic static final String First_String = "Str1";
.