Java Nested Switch Statements
We can use a switch as part of the statement sequence of an outer switch. This is called a nested switch. Since a switch statement defines its block, no conflicts arise between the case constants in the inner switch and those in the outer switch.
Example:
Nested Switch Statement
// Java Program to Demonstrate
// Nested Switch Case Statement
// Class
public class GFG {
// Main driver method
public static void main(String[] args)
{
// Custom input string
String Branch = "CSE";
int year = 2;
// Switch case
switch (year) {
// Case
case 1:
System.out.println(
"elective courses : Advance english, Algebra");
// Break statement to hault execution here
// itself if case is matched
break;
// Case
case 2:
// Switch inside a switch
// Nested Switch
switch (Branch) {
// Nested case
case "CSE":
case "CCE":
System.out.println(
"elective courses : Machine Learning, Big Data");
break;
// Case
case "ECE":
System.out.println(
"elective courses : Antenna Engineering");
break;
// default case
// It will execute if above cases does not
// execute
default:
// Print statement
System.out.println(
"Elective courses : Optimization");
}
}
}
}
Output
elective courses : Machine Learning, Big Data
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.