Reputation: 6527
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.
Upvotes: 4
Views: 1092
Reputation: 16050
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,
Upvotes: 4
Reputation: 26961
You must declare Constants
as final
public static final String First_String = "Str1";
public static final String Second_String = "Str2";
public static final String Third_String = "Str3";
Or transform switch
in if-else
statement:
In Eclipse
You can quickly convert a switch
statement to an if-else
statement using the following:
Move your cursor to the switch
keyword and press Ctrl + 1 then select
Convert 'switch' to 'if-else'.
Upvotes: 1
Reputation: 1648
Change
public static String First_String = "Str1";
to
public static final String First_String = "Str1";
Now it is a constant.
Upvotes: 2
Reputation: 59095
The strings in your Constants
class must be declared final
to be regarded as constants.
If they are declared final
, the compiler knows they can never change, so can treat them as constant expressions. If they are not declared final
, the possibility exists they might be reassigned to different strings during the execution of the program, so they are not constants.
Upvotes: 1
Reputation: 62864
"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";
Upvotes: 7