Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java switch cases: with or without braces?

Consider the following two snippets, with braces:

switch (var) {   case FOO: {     x = x + 1;     break;   }    case BAR: {     y = y + 1;     break;   } } 

Without braces:

switch (var) {   case FOO:     x = x + 1;     break;    case BAR:     y = y + 1;     break; } 

I know that, in the snippet with braces, a new scope is created by enclosing each case in braces. However, if each case does not need the new scope (i.e. no variable names are being reused), is there any sort of performance penalty for using the braces with a case?

like image 725
cdmckay Avatar asked Mar 11 '09 06:03

cdmckay


People also ask

Do you need braces in switch-case?

The braces are always needed following the switch statement. No braces are needed following any case. If the variable is equal to one of the values following a case, then the code following the case is executed.

Do switch cases need curly braces?

Bookmark this question. Show activity on this post. In a C switch-case flow control, it's required to put curly braces { } after a case if variables are being defined in that block.

Are braces necessary in Java?

Braces { } not required for one statement (but are always good) If the true or false clause of an if statement has only one statement, you do not need to use braces (also called "curly brackets"). This braceless style is dangerous, and most style guides recommend always using them.

Are switch cases good to use in Java?

The switch case in java executes one statement from multiple ones. Thus, it is like an if-else-if ladder statement. It works with a lot of data types. The switch statement is used to test the equality of a variable against several values specified in the test cases.


1 Answers

is there any sort of performance penalty for using the braces with a case?

None.

The curly braces are there to help the compiler figure out the scope of a variable, condition, function declaration, etc. It doesn't affect the runtime performance once the code is compiled into an executable.

like image 162
MrValdez Avatar answered Oct 16 '22 05:10

MrValdez