Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Help with switch statement

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

like image 944
javabeginner Avatar asked Aug 09 '11 14:08

javabeginner


People also ask

How do you break out of a switch statement?

You can use the break statement to end processing of a particular labeled statement within the switch statement. It branches to the end of the switch statement. Without break , the program continues to the next labeled statement, executing the statements until a break or the end of the statement is reached.

How does a switch statement work?

A switch works with the byte , short , char , and int primitive data types. It also works with enumerated types (discussed in Enum Types), the String class, and a few special classes that wrap certain primitive types: Character , Byte , Short , and Integer (discussed in Numbers and Strings).

What is switch statement example?

So, printf(“2+3 makes 5”) is executed and then followed by break; which brings the control out of the switch statement. Other examples for valid switch expressions: switch(2+3), switch(9*16%2), switch(a), switch(a-b) etc.


2 Answers

No, you don't have to. If you omit the break statement, however, all of the remaining statements inside the switch block are executed, regardless of the case value they are being tested with.

This can produce undesired results sometimes, 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 would be your result:

You got an A!
You got a B.
You got a C.
You got a D.
You failed. :(
like image 117
fireshadow52 Avatar answered Oct 23 '22 07:10

fireshadow52


You don't have to break after each case, but if you don't they will flow into each other. Sometimes you want to bundle multiple cases together by leaving out the breaks.

like image 5
jpredham Avatar answered Oct 23 '22 09:10

jpredham