break in switch case Statements
A break statement is optional. If we omit the break, execution will continue into the next case.
It is sometimes desirable to have multiple cases without “break” statements between them. For instance, let us consider the updated version of the above program, it also displays whether a day is a weekday or a weekend day.
Example:
Switch statement program without multiple breaks
// Java Program to Demonstrate Switch Case
// with Multiple Cases Without Break Statements
// Class
public class GFG {
// main driver method
public static void main(String[] args)
{
int day = 2;
String dayType;
String dayString;
// Switch case
switch (day) {
// Case
case 1:
dayString = "Monday";
break;
// Case
case 2:
dayString = "Tuesday";
break;
// Case
case 3:
dayString = "Wednesday";
break;
case 4:
dayString = "Thursday";
break;
case 5:
dayString = "Friday";
break;
case 6:
dayString = "Saturday";
break;
case 7:
dayString = "Sunday";
break;
default:
dayString = "Invalid day";
}
switch (day) {
// Multiple cases without break statements
case 1:
case 2:
case 3:
case 4:
case 5:
dayType = "Weekday";
break;
case 6:
case 7:
dayType = "Weekend";
break;
default:
dayType = "Invalid daytype";
}
System.out.println(dayString + " is a " + dayType);
}
}
Output
Tuesday is a Weekday
Switch Statements in Java
The switch statement in Java is a multi-way branch statement. In simple words, the Java switch statement executes one statement from multiple conditions.
It is like an if-else-if ladder statement. It provides an easy way to dispatch execution to different parts of code based on the value of the expression. The expression can be a byte, short, char, or int primitive data type. It tests the equality of variables against multiple values.