Java – why can’t the final variable be used in a switch statement?

When I type the following code in eclipse, it complains that "case expressions must be constant expressions." If the array is marked final, its contents must be constants Why is this invalid?

final String[] match={"a","b","c"};
switch (switchVar) {
case match[0]: /* Eclipse complains here about nonconstant switch */
    System.out.println("Matches");
    break;
default:
    System.out.println("No Match");
    break;
}

Solution

The array does not have any constants Its content may change at any time The reference will say the same, but the match [0] may be different at any point in time

You must use a constant value; A promise will not change Enumeration, original text (and its boxed counterpart) and string text are guaranteed not to change in this process, and can be used

However, this does mean that you can use variables marked final and immutable Because the array type is mutable, it doesn't work - even if you reassign it to the final variable You must declare the text

Here is a simple code snippet to modify the existing code:

String switchVar = "a";
final String matchZero = "a";
switch (switchVar) {
    case matchZero: // valid since there's no way matchZero can ever be mutated
        System.out.println("Matches");
        break;
    default:
        System.out.println("No Match");
        break;
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>