Switch case
The switch statement is used when there is multiple options to be tested for equality against a single switch variable and each option may have a different task to perform. A switch statement works with the byte, short, char, int primitive data types, enum Types, the String class, and a few special classes that wrap certain primitive types: Character, Byte, Short, and Integer. Nesting of switch statement is possible, which means creating of the switch statement inside another switch statement.
Syntax
switch(expression){
case 1:
//code to be executed
break;//optional
case 2:
//code to be executed
break; //optional
case 3:
//code to be executed
break; //optional
default:
/*default code to be executed if none
* of the above cases are matched.*/
}
Example
A program to output the name of the month, based on the provided integer value to the month variable, using the switch case statement:
public class SwitchExample {
public static void main(String[] args) {
/* Declaring a variable for switch expression. */
int month = 5;
String monthString;
// switch expression.
switch (month) {
// case statements.
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 case statement.
default:
monthString = "Invalid month";
break;
}
System.out.println(monthString);
}
}
Output
The case statement
The case statement is used with the switch statement. A case statement contains a block of code which is executed only when the switch value matches the case.
The break statement
The break statement inside a loop, immediately terminates the loop and the program control resumes at the next statement following the loop. Execution of code will continue on into the next case if the break statement is omitted. The use of the break statement is optional.
The default statement
The default keyword in switch statement specifies a block of code to run if there is no case match in the switch. The use of the default keyword is optional.