Java switch : variable declaration and scope

后端 未结 7 632
予麋鹿
予麋鹿 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:44

    You can define the scope using {} around your case.

    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);
        int b = 2;
        System.out.println("case 1 after: b = " + b);
        break;
    }
    default: {
        int b = 7;
        System.out.println("default: b = " + b);
    }
    }
    

提交回复
热议问题