How break is useful with switch statement in Java?
The break statement is used to terminate the statement sequence in a switch statement. If we do not use break statement, the control of flow of the switch continue as usual and just work like an else-if ladder.
The below program print the month name on the screen according to the provided number.
Program:
import java.util.Scanner;
public class SwitchBreakDemo {
public static void main(String[] args) {
int month;
System.out.println("Enter a number to display its corresponding Month Name");
Scanner in = new Scanner(System.in);
month=in.nextInt();
String monthString;
switch (month) {
case 1: monthString = "January";
break;
case 2: monthString = "February";
break;
case 3: monthString = "March";
break;
case 4: monthString = "April";
break;
case 5: monthString = "May";
break;
case 6: monthString = "June";
break;
case 7: monthString = "July";
break;
case 8: monthString = "August";
break;
case 9: monthString = "September";
break;
case 10: monthString = "October";
break;
case 11: monthString = "November";
break;
case 12: monthString = "December";
break;
default: monthString = "Invalid month";
break;
}
System.out.println(monthString);
}
}
Output:
Enter a number to display its corresponding Month Name
5
May