I am relatively new to java. In a switch
statement, do you have to put a break
statement after each case
?
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.
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).
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.
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. :(
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With