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