In Java, is it possible to use the method / constructor parameter as a switch statement, a case constant?

In the case of the switch, I noticed that when I try to use the parameter as a case constant, I get a compilation error. But I can use fields / local vars.

Is it really impossible to use a parameter as a case constant? Or are there exceptions (if yes, provide an example)?

Example:

final int field = 0;
void method( final int parameter) {
    switch( 3) {
        case field: // ALLOWED
        case parameter; // NOT ALLOWED
    }
}

I am trying to use a parameter directly. I do not need solutions that store the parameter value in the local var.

+5
source share
2 answers

Like C and C ++, Java only allows compile-time constants as a value for case.

final . final .

, , if...else....

EDIT:

, . final case.

+3

java case

+2

All Articles