The switch statement is a multiway branch statement. It gives an easy way to execute the different parts of the programs based on the value of the expression. The expression can be shot, byte, short, char, and int primitive data type.
Syntax of switch-case
// switch statementswitch(expression){// case statements// values must be of same type of expressioncase value1 :// Statementsbreak; // break is optionalcase value2 :// Statementsbreak; // break is optional// We can have any number of case statements// below is default statement, used when none of the cases is true.// No break is needed in the default case.default :// Statements}
Flowchart of the Switch case:
Rules
- You can not take duplicate case values.
- case value must be of the same data type as the variable in the switch.
- case value must be a constant or a literal.
- Variables are not allowed.
- The break statement is used inside the switch to terminate the sequence of the statement.
- The default statement is optional and can appear anywhere inside the switch block.
Example
Consider the following java program, it declares an int named day whose value represents a day(1-7). The code displays the name of the day, based on the value of the day, using the switch statement.
Code
public class Switch1 {public static void main(String args[]){int a = 1;String DayS;String DayString;switch (a) {case 1:DayString="Monday";break;case 2:DayString="Tuesday";break;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 Number";break;}switch (a) {case 1:case 2:case 3:case 4:case 5:DayS ="Weekday";break;case 6:DayS="Weekend";break;case 7:DayS="Weekend";break;default:DayS ="Invalid Number";break;}System.out.println(DayString +" is a "+ DayS);}}
Output
Monday is a Weekday
0 Comments