peer
peer

Reputation: 4719

final variable not const enough for switch case

I have the following code:

public class Main {

    static final String fu = Week.class.getName();

    public static void main(String[] arg0){

        String h = "dummy";
        switch (h) {
*        case fu:
            System.out.println(8);
            break;
        default:
            break;
        }
    }
}

Now Eclipse complains at * that case expressions must be constant expressions. But I made fu as constant as I know to do! Why is this not enough, what can I do (other than if-else)?

Upvotes: 0

Views: 339

Answers (2)

Narendra Jaggi
Narendra Jaggi

Reputation: 1338

I got the issue seems like compiler expects a value at compile time so as to make the your string variable as constant.
In your case class name is coming @ runtime not at compile time so compiler will not consider that as a constant For a variable to be constant
- INITIALIZED WITH CONSTANT EXPRESSION ONLY
- should be declare as final
-primitive or String
- initialize while declaration

So you void the 1st condition. Just for reference check the following program-
Here case x will give error as it is coming @ runtime from class. But if set it to some constant like 20 it will run fine.

  package com;

    public class Main {

    static final int x = Week.getx();

    public static void main(String[] arg0){

        int i = 10;
        switch (i)
        {
        case x : System.out.println("Hello"); break;

        case 12 : System.out.println("Bye"); break;

        }

            }
}

package com;

public class Week {

public static int  getx()
{
    return 10;
}
}


Tell if you need more explanation!

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1502835

Why is this not enough

Because it's not a compile-time constant by the rules of JLS 15.28.

Why is this not enough, what can I do (other than if-else)?

Nothing, basically - unless you use a string literal, which would obviously not be very pleasant.

Upvotes: 4

Related Questions