Java - switch statement and curly braces

I have a question related to braces in a case switch block

 switch( conditon ) { 

   case val1: {
      // something 
   }
   break;
   case val2: {
      // something 
   }
   break; 
   default:
   break;  
}

or something like this:

 switch( conditon ) { 

   case val1: {
      // something 
      break;
   }
   case val2: {
      // something 
      break;
   } 
   default:
   break;  
}

A I know that both codes should work the same way, but I think there are some irrationalities here. Since the break should go out of curly brackets, theoretically the second code should smooth like this: 1. Break the course jumping out of block 2. switch continues to execute case val2 or by default there is no break statement outside the brackets.

Which version do you recommend to use and do they really work the same?

+4
source share
2 answers

Try the following:

{
System.out.println("A");
break;
System.out.println("B");
}

You will see

$ javac Y.java 
Y.java:35: error: break outside switch or loop
    break;
    ^
1 error

: , .

, , ( ). , , , .

+5

. , , , , .. , ,

+2

All Articles