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.
"Str1"
is a compile-time constant and that's why case "Str"
is fine.
However, the from the definition of First_String
we can see that it is not a constant, because it can change it's value at any time.
You can try setting it as final
:
public static final String First_String = "Str1";
A constant expression is not the same as a static member. Even a static member can be changed by code... It needs to be final
to be considered a constant expression:
From the JLS:
A compile-time constant expression is an expression...
- Simple names (§6.5.6.1) that refer to constant variables (§4.12.4).
So
case "Something":
is OK. As is
public static final String ME = "Other";
...
case ME:
Finally, enum
's are also OK to use in switch
-case
statements.
Cheers,
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With