Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

In a switch case, I've noticed that when I try to use a 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 so, please provide an example)?

Example:

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

I'm trying to use the parameter directly. I'm not interested in solutions that save the value of the parameter in a local var.

like image 304
John Assymptoth Avatar asked Jan 31 '11 16:01

John Assymptoth


1 Answers

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

The value of initialised final class members can be determined at compile time and cannot change. final method parameters can have a different value at each method call.

To compare with method parameters, you probably have to fall back on good-old if...else....

EDIT:

By the way, note the emphasis on initialised above. A final class member without an initialiser at the declaration cannot be used in as a case value either.

like image 115
thkala Avatar answered Sep 28 '22 03:09

thkala