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 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.

+4
source share
5 answers

"Str1"is a compile-time constant, and therefore case "Str"excellent.

However, from the definition First_Stringwe can see that it is not a constant, because it can change its value at any time.

final:

public static final String First_String  = "Str1";
+6

A - , . ... final :

JLS:

...

  • (§6.5.6.1), (§4.12.4).

,

case "Something":

.

public static final String ME = "Other";
...
case ME:

, enum switch - case.

,

+4

public static String First_String  = "Str1";

to

public static final String First_String  = "Str1";

.

+2

Constants final .

final, , , . final, , , .

+1

Constants final

public static final String First_String  = "Str1";
public static final String Second_String = "Str2";
public static final String Third_String  = "Str3";

switch if-else:

Eclipse
switch if-else, :

switch Ctrl + 1,

'' 'if-else'.

+1

Source: https://habr.com/ru/post/1588977/


All Articles