Help with the switch statement

I am relatively new to java. In the switch do you need to put a break statement after each case ?

+6
source share
6 answers

No, you don’t have to. However, if you omit the break statement, all other statements inside the switch block are executed regardless of the case value that they are testing with.

This can sometimes lead to undesirable results, as in the following code:

 switch (grade) { case 'A': System.out.println("You got an A!"); //Notice the lack of a 'break' statement case 'B': System.out.println("You got a B!"); case 'C': System.out.println("You got a C."); case 'D': System.out.println("You got a D."); default: System.out.println("You failed. :("); } 

If you set the grade variable to "A", this will be your result:

 You got an A! You got a B. You got a C. You got a D. You failed. :( 
+7
source

You do not need to break after each case, but if you do not, they will flow into each other. Sometimes you want to combine several cases together, leaving gaps.

+5
source

It is better. Otherwise, the following statements will be executed.

 switch(someNumber) { case thisCaseMatches: doThat(); case thisCaseDoesNotMatch: shouldntExecuteYetItWillBeExecuted(); default: alsoWillbeExecuted(); } 
+3
source

If you do not exit the switch with return or another action.

+3
source

Semantically yes. Otherwise, all case statements will be executed after the first match.

+2
source

It is good practice to take a break after each statement.

You are not forced.

But if you do not set breaks tatement, you have a cascading switch statement, namely a larger condition can be matched, and sometimes it can lead to logical errors.

However, there are people who believe that cascading statements can optimize code by helping to write less code.

+2
source

Source: https://habr.com/ru/post/894636/


All Articles