[Java] [Java] A constant expression must be entered when a character string is entered in the case of a switch statement

1 minute read

I don’t think I know it now, but I didn’t know it, so I wrote it for myself. I’ll forget it soon.

This example gives a compile error

For example

public class SwitchTest {
    static final String ddd = "ddd";
    static String ccc = "ccc";
    public static void main(String[] args) {

        String bbb = "bbb";

        final String eee = "eee";

        switch(args[0]) {
            case "aaa":
                System.out.println("aaa");
                break;
            case bbb:
                System.out.println("bbb");
                break;
            case ccc:
                System.out.println("ccc");
                break;
            case ddd:
                System.out.println("ddd");
                break;
            case eee:
                System.out.println("eee");
                break;
            default:
                System.out.println("default");
                break;
        }
    }

Suppose you wrote the code But this gives a compilation error. By the way, the following error appears.


SwitchTest.java:14: ERROR: constant string expression expected
            case bbb:
                 ^
SwitchTest.java:17: ERROR: constant string expression expected
            case ccc:
                 ^

In short, it seems that the string entered in case must be a “constant” (final clause is required). In fact, ddd (static final) and eee (final) have not been extracted as compilation errors. Also, if you write a character string directly to the case ("aaa"), it seems to be treated as a “constant” here and it will not be extracted as a compilation error. Well, it’s not a “variable”. ..

In addition, since the output returned as a compile error is used as it is, the keyword “constant” is brought out. To be exact, is this the name “constant”? Expression? It doesn’t seem to be. This area is written in here. Since it is a Constant Expression, is it correct to say “constant expression” in Japanese? For example, according to this, the operation using ``+’’ seems to be a “constant expression”,

...
    case "aaa" + "xxx":
        System.out.println("aaa+xxx");
        break;
...

Compiling can be done with this. However, if you use "aaa" + bbb with a variable that has not been finalized (for example, bbb above), you will get a compile error.

I didn’t know it because I didn’t use switch statement as a string. I learned a lot. (?)

Tags:

Updated: