[Java] When putting a character string in the case of a switch statement, it is necessary to make it a constant expression

I think it feels pretty good now, but I didn't know it, so it's a memo for myself. I'll forget it soon.

An example like this will result in 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 write the code. However, this results in a compilation error. By the way, the following error appears.


SwitchTest.java:14:error:Requires a constant string expression
            case bbb:
                 ^
SwitchTest.java:17:error:Requires a constant string expression
            case ccc:
                 ^

In short, it seems that the string to put in the case must be a "constant" (requires a final clause). In fact, ddd ( static final) and eee ( final) are not extracted as compilation errors. Also, if you write a character string directly in the case ("aaa"), it will be treated as a "constant" here and will not be extracted as a compile error. Well, it's not a "variable". ..

Since the output returned as a compile error is used as it is, the keyword "constant" is brought up, but to be precise, is this the name "constant"? Expression? It doesn't seem to be. This area is described in here. Since it is a constant expression, is it correct to say "constant expression" in Japanese? For example, according to this, operations using + also seem to correspond to "constant expressions".

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

This also compiles. However, if you use a variable that does not have final as the join target (for example, bbb mentioned above) and do "aaa" + bbb, you will get a compile error.

I didn't know it until now because I didn't often use switch statements in strings. I learned a lot. (?)

Recommended Posts

[Java] When putting a character string in the case of a switch statement, it is necessary to make it a constant expression
Make the JSON of the snake case correspond to the field of the camel case in Java (JVM)
[Java] Is it unnecessary to check "identity" in the implementation of the equals () method?
[Java] Cut out a part of the character string with Matcher and regular expression
[Java] Make it a constant
I tried to make a client of RESAS-API in Java
[Java] It seems that `0 <hoge <10` cannot be written in the conditional expression of the ʻif` statement.
String Replacement of the case where the regular expression * of the character string search condition contains a line break.
[Swift] When you want to know if the number of characters in a String matches a certain number ...
When the character string passed to C ++ by JNA is garbled
About the method to convert a character string to an integer / decimal number (cast data) in Java
A program that searches for a character string, and when the search character string is found, displays the character string from the beginning of the line to just before the search character string.
The milliseconds to set in /lib/calendars.properties of Java jre is UTC
Let's create a TODO application in Java 5 Switch the display of TODO
How to check for the contents of a java fixed-length string
[Java beginner] Conversion from character string to numerical value-What is the parseInt method of the Integer class? ~
The story of forgetting to close a file in Java and failing
Memo: [Java] If a file is in the monitored directory, process it.
[Java] How to use substring to cut out a part of a character string
[Java small story] Monitor when a value is added to the List
[Java] How to get to the front of a specific string using the String class
How to find the total number of pages when paging in Java
How to get the absolute path of a directory running in Java
[Java] Check if the character string is composed only of blanks (= Blank)
[Swift] Rather, it is meaningful to avoid var and declare it with let only when there is a branch in the assignment of the initial value.
When I wanted to create a method for Premium Friday, it was already in the Java 8 standard API
[Note] [Beginner] How to write when changing the value of an array element in a Ruby iterative statement
Since the image of the lock screen of Windows 10 is beautiful, I wanted to make it a slide show of wallpaper
[Java] Difference between equals and == in a character string that is a reference type
[Java] How to easily get the longest character string of ArrayList using stream
Isn't there a name collision when enum has the same name in the switch statement?
How to make a unique combination of data in the rails intermediate table
Is it mainstream not to write the closing tag of <P> tag in Javadoc?
Cause of is not visible when calling a method of another class in java
Conditional branching of the result of SQL statement to search only one in Java
Be absolutely careful when putting the result of and / or in a variable!
The story of low-level string comparison in Java
Java switch statement and break, Kotlin when expression ...
Make a margin to the left of the TextField
Measure the size of a folder in Java
I wanted to make (a == 1 && a == 2 && a == 3) true in Java
Even if I want to convert the contents of a data object to JSON in Java, there is a circular reference ...
I want to find the MD5 checksum of a file in Java and get the result as a string in hexadecimal notation.
Pass the condition to be used in the Java8 lambda expression filter () as a parameter
[Java] Incompatible types error occurred when assigning a character string to a char type variable
How to get the class name of the argument of LoggerFactory.getLogger when using SLF4J in Java
# 1_JAVA I want to get the index number by specifying one character in the character string.
Summary of how to use the proxy set in IE when connecting with Java
Count the number of occurrences of a string in Ruby
When the hover of Eclipse is hard to see
I tried to make a login function in Java
[Java] When writing the source ... A memorandum of understanding ①
[Java] How to cut out a character string character by character
[Java] How to erase a specific character from a character string
How to perform a specific process when the back button is pressed in Android Fragment
[Ruby] Get in the habit of using the dup method when making a copy of a string variable
It is difficult to use the empty string or date of DBUnit, so fix it and use it.
When I switched to IntelliJ, I got a lot of differences in the encoding of the properties file.
If you want to make a Java application a Docker image, it is convenient to use jib.
Considering the adoption of Java language in the Reiwa era ~ How to choose a safe SDK
Use JLine when you want to handle keystrokes on the console character by character in Java