Frosted Cupcake
Frosted Cupcake

Reputation: 1970

Why does the case statement doesn't take variables?

I know that this is a silly question,but I wanted to know why the case label doesn't take variables. The code is-

public class Hello
{
    public static void main(String[] args)
    {
        final int y=9;
        int a=1,b=2,c=3;
        switch(9)
        {
            case y:
            {
                System.out.println("Hello User");
                break;
            }
            case a:
            {
                System.out.println("Hello World");
                break;
            }
            case b:
            {
                System.out.println("Buff");
                break;
            }
            default:
            {
                System.out.println("Yo bitch");
                break;
            }
        }
    }
}

Although, I have initialized a,b and c,yet it is showing errors.Why?

Upvotes: 1

Views: 107

Answers (3)

Mena
Mena

Reputation: 48444

Your a, b, c ints are not constants.

You can simply prepend final to their inline declaration and assignment to make your code compile.

Now of course, you're left with a switch statement that compares 9 with other values, which might not be terribly useful.

Note

As still-learning mentions, here's the documentation.

Upvotes: 2

Leah
Leah

Reputation: 458

Proper code might be:

public class Hello
{
    public static void main(String[] args)
    {
        final int y=9;
        int a=1,b=2,c=3;
        switch(y) //here comes y, the variable
        {
            case 1: //here are the cases - numbers
            {
                System.out.println("Hello User");
                break;
            }
            case 2:
            {
                System.out.println("Hello World");
                break;
            }
            case 3:
            {
                System.out.println("Buff");
                break;
            }
            default:
            {
                System.out.println("Yo bitch");
                break;
            }
        }
    }
}  

Upvotes: 0

Konstantin Yovkov
Konstantin Yovkov

Reputation: 62874

Actually, it does take variables, but they must be final.

If you do:

final int a = 1, b = 2, c = 3;

then it will compile just fine.

As a side note, having switch (9) and maintaining a list of case blocks, doesn't make much sense, as only one of the case(s) is actually reachable.

Upvotes: 5

Related Questions