Revanth Penugonda Revanth Penugonda - 5 months ago 13
Java Question

can I declare variables with the same name in every Case branch of a Switch-Case?

I am trying to create a generic class object in switch case with same name I get a error for duplicate variable. Is there a way to create the object without changing the name of the object.

switch (ch) {
case 1:
Example<Integer> ex = new Example<Integer>();
break;
case 2:
Example<Float> ex = new Example<Float>();
break;
case 3:
Example<String> ex = new Example<String>();
break;
default:
System.out.println("");
break;
}

Answer

You need to move your variable declaration outside the switch block as next:

Example<?> ex;
switch (ch) {
    case 1:
        ex = new Example<Integer>();
        break;
    case 2:
        ex = new Example<Float>();
        break;
    case 3:
        ex = new Example<String>();
        break;
    default:
        throw new IllegalArgumentException("Unknown type " + ch);
}

As you mixed several types that have nothing in common, you have to use the wildcard for unknown type.

Comments