Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java switch : variable declaration and scope

How does the Java compiler handle the following switch block ? What is the scope of the 'b' variable ?

Note that the 'b' variable is declared only in the first branch of the switch statement. Attempting to declare it in the second branch as well results in a "duplicate local variable" compilation error.

    int a = 3;
    switch( a ) {
    case 0:
        int b = 1;
        System.out.println("case 0: b = " + b);
        break;
    case 1:
        // the following line does not compile: b may not have been initialized
        // System.out.println("case 1 before: b = " + b);
        b = 2;
        System.out.println("case 1 after: b = " + b);
        break;
    default:
        b = 7;
        System.out.println("default: b = " + b);
    }

Note: the above code compiles with a java 1.6 compiler.

like image 425
Marius Ion Avatar asked Jun 07 '12 13:06

Marius Ion


People also ask

Can we declare variables in switch case Java?

Do not declare variables inside a switch statement before the first case label. According to the C Standard, 6.8.

Can you declare variables in a switch?

Declaring a variable inside a switch block is fine. Declaring after a case guard is not.

Can we give range in switch case in Java?

Case ranges and case labels can be freely intermixed, and multiple case ranges can be specified within a switch statement.

What variables are used in a switch statement?

A switch works with the byte , short , char , and int primitive data types.


1 Answers

The scope of b is the block. You have only one block which includes all cases. That's why you get a compile error when you redeclare b in your second case.

You could wrap each case in an own block like

case 0:
   {
     int b = 1;
     ...
   }
case 1:
   {
     int b = 2;
     ...
   }

but I think FindBugs or CheckStyle would complain about that.

like image 66
Kai Avatar answered Sep 28 '22 08:09

Kai