Flowchart of Switch-Case Statement
This flowchart shows the control flow and working of switch statements:
Note: Java switch statement is a fall through statement that means it executes all statements if break keyword is not used, so it is highly essential to use break keyword inside each case.
Example: Finding Day
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.
// Java program to Demonstrate Switch Case
// with Primitive(int) Data Type
// Class
public class GFG {
// Main driver method
public static void main(String[] args)
{
int day = 5;
String dayString;
// Switch statement with int data type
switch (day) {
// Case
case 1:
dayString = "Monday";
break;
// Case
case 2:
dayString = "Tuesday";
break;
// Case
case 3:
dayString = "Wednesday";
break;
// Case
case 4:
dayString = "Thursday";
break;
// Case
case 5:
dayString = "Friday";
break;
// Case
case 6:
dayString = "Saturday";
break;
// Case
case 7:
dayString = "Sunday";
break;
// Default case
default:
dayString = "Invalid day";
}
System.out.println(dayString);
}
}
Output
Friday
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.