1

I'm not new to Java but this is a thing that i have never seen before.
Supposing have a switch case, declaring a variable in case 0 makes the variable visible in the other cases that is a strange thing and i think is not in the java style.

public static void main(String[] args) {
    String _case = "case";

    switch (_case) {
        case "1":
            String foo = "foo";
            break;
        case "2":
            String bar = "bar";
            break;
        case "case":
            foo = "foo";
            System.out.println(foo);
            // System.out.println(bar); //Variable bar might not have been initialized
            break;
    }
}

If case 1 is not validated why and how the String foo variable becomes declared?

Execute the code online

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Roberto Manfreda
  • 2,345
  • 3
  • 25
  • 39

1 Answers1

0

Because you set foo = "foo" inside of your last case, it guarantees the variable was instantiated at that point. There's no moment in which bar is instantiated in the last case, giving you this error. This is due to the fact that the scope of a variable in a case is equal to that of the entire switch statement. More info on other questions about this

Ferdz
  • 1,182
  • 1
  • 13
  • 31