Java switch : variable declaration and scope

后端 未结 7 664
予麋鹿
予麋鹿 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 switch block - between the declaration and the delimiter } -

    int a = 3;
    
    switch( a ) {
         case 0:
              int b = 1; //scope starts
              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);
    }//scope ends
    

    However, you need to know that if you declare the int b inside the case 1:, you will NOT have access to the variable b inside the case 0:

    To answer the question you ask in the java comments you can check this simpler example:

    int b;
    if(true){
        b++; //The local variable b hast not been initialized
    }
    

    Hope it helps.

提交回复
热议问题