Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Switch statement and curly braces

I have a question associated with curly braces in switch-case 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 both codes should work the same way but I think there is some irrationalities here. As the break should cause jumping out from curly braces block so theoretically second code should do smoothen like this: 1. break course jumping out of block 2. switch continues execution case val2 or default cause outside the braces there isn't any break statement.

Which version you recommend to use and Are they really working the same way?

like image 757
Michał Ziobro Avatar asked Mar 26 '15 09:03

Michał Ziobro


2 Answers

Try this:

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

You'll see

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

This means: you can't use it in a block, it has no effect in combination with a block.

I would not put the break outside the block, but I've never seen coding rules demanding either way (and you could put up arguments for both sides). Maybe this is because blocks aren't used very frequently to separate visibility per switch branches.

like image 73
laune Avatar answered Sep 30 '22 18:09

laune


Curly braces limit the scope of variables. And have no effect on flow control other than if, for, while, switch.. blocks, except for the cases where they're optional

like image 23
yiabiten Avatar answered Sep 30 '22 19:09

yiabiten