Java switch : variable declaration and scope

后端 未结 7 667
予麋鹿
予麋鹿 2020-12-11 03:14

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 b

7条回答
  •  春和景丽
    2020-12-11 03:59

    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.

提交回复
热议问题