Java switch: variable declaration and scope

How does the Java compiler handle the next block of radio buttons? What is the scope of the variable "b"?

Note that the variable 'b' is only declared in the first branch of the switch statement. An attempt to declare it in the second branch also leads to a compilation error "duplicate local variable".

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 is compiled using the java 1.6 compiler.

+7
source share
7 answers

Volume, as usual, is limited { and } .

+21
source

Volume b is a block. You have only one block that includes all case s. This is why you get a compilation error when you update b in the second case .

You can wrap each case in its own block, for example

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

but I think FindBugs or CheckStyle will complain about it.

+10
source

Volume b is the switch block - between declaration and 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 int b inside case 1: you will NOT have access to the variable b inside case 0:

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

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

Hope this helps.

+3
source

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); } } 
+3
source

in your code, if a is not 0 b, it will never be initialized. you must define b before the switch statement.

+1
source

There is no local scope in case blocks. This is not a series of if ... else if ... else blocks, java implements it as a series of GOTO s.

0
source

The scope of the variables defined in the switch() will be the same as in a regular block surrounded by { and } .

Therefore, each variable defined in the switch() is visible to the entire block as soon as it is defined.

0
source

All Articles