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 class Constants,
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 since
Exception in thread "main" java.lang.Error: unresolved compilation problems: case expression must be constant expressions
But when I tried using the 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");
}
There are no compilation errors and displays the result as
First String
My question is why in the first case an addition error occurs. And how can I resolve it.
source
share