Switch Case Statement
Lesson 6 of 11 in Coddy's Control Statements in Java course.
If-else-if statements are similar to switch statements.
The switch statement contains multiple blocks of code called cases, and a single case is executed based on the variable that is being switched.
There are several possible execution paths.
There can be N number of cases.
Every case should be unique.
For example, you want to know which month it is by entering the input as a month number, so the Switch statement can be used.
Each case statement can have a break as an optional feature.
Syntax:
switch(expression){
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......
default:
// code to be executed if all cases are not matched;
}Challenge
EasyWrite a switch case program to implement Days of the Week.
Take int as input, and the week starts on Monday, so print the day accordingly.
Example: if input is 4, then it should print "Thursday".
The default case is "Invalid"
Try it yourself
class DayOfWeek {
public static String dayOfWeek(int day) {
// Write code here
}
}All lessons in Control Statements in Java
1What are Control Statements?
Introduction2Decision Making Statments
Simple if Statementif-else Statementif-else-if StatementNested if-StatementSwitch Case Statement