Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switch statement with string

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.

like image 870
Rakesh KR Avatar asked Dec 09 '22 03:12

Rakesh KR


2 Answers

"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";
like image 110
Konstantin Yovkov Avatar answered Dec 11 '22 10:12

Konstantin Yovkov


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,

like image 33
Anders R. Bystrup Avatar answered Dec 11 '22 10:12

Anders R. Bystrup