Nested Switch

In Java, a nested switch is a construct where one switch statement is nested within another. This means that there is a switch statement inside the body of another switch statement. Each switch statement consists of multiple case labels and corresponding code blocks. The inner switch statement is enclosed within the code block of one of the outer switch statement’s cases.

Syntax for nested switch statement:

switch (outerExpression) {

case outerValue1:

        // Code block for outerValue1

        switch (innerExpression) {

case innerValue1:

            // Code block for innerValue1

            break;

case innerValue2:

        // Code block for innerValue2

        break;

    // More inner cases…

}

break;

case outerValue2:

        // Code block for outerValue2

        switch (innerExpression) {

            // Inner cases for outerValue2…

       }

break;

  // More outer cases…

}

In this example, there is an outer switch statement based on the outerExpression, and within each outer case, there is an inner switch statement based on the innerExpression. Depending on the values of outerExpression and innerExpression, the appropriate code blocks associated with the matched cases are executed.

Nested switches can be useful when you need to make multi-level decisions based on multiple criteria. However, nested switches can also make the code harder to read and maintain, especially when they become deeply nested. In some cases, it might be better to refactor the code to use other control structures or to break down the logic into smaller, more manageable functions.

It’s important to note that while nested switches can be used, it’s generally a good practice to keep your code as simple and clear as possible. If you find that your code is becoming overly complex with nested switches, consider alternative approaches such as using polymorphism, data structures, or separate functions to improve code readability and maintainability.

Let’s consider a simple example to demonstrate the concept of nested switch statements in Java. Imagine you’re building a program that provides information about different types of vehicles based on their category and subcategory.

public class NestedSwitchExample {
    public static void main(String[] args) {
        String vehicleCategory = "Car";
        String vehicleSubcategory = "Sedan";
        
        switch (vehicleCategory) {
            case "Car":
                System.out.println("Vehicle Category: Car");
                switch (vehicleSubcategory) {
                    case "Sedan":
                        System.out.println("Vehicle Subcategory: Sedan");
                        System.out.println("Sedans are known for their comfortable ride.");
                        break;
                    case "SUV":
                        System.out.println("Vehicle Subcategory: SUV");
                        System.out.println("SUVs are popular for their off-road capability.");
                        break;
                    default:
                        System.out.println("Unknown Vehicle Subcategory");
                        break;
                }
                break;
            case "Motorcycle":
                System.out.println("Vehicle Category: Motorcycle");
                switch (vehicleSubcategory) {
                    case "Sport":
                        System.out.println("Vehicle Subcategory: Sport");
                        System.out.println("Sport motorcycles are built for high-speed performance.");
                        break;
                    case "Cruiser":
                        System.out.println("Vehicle Subcategory: Cruiser");
                        System.out.println("Cruisers are designed for relaxed, long rides.");
                        break;
                    default:
                        System.out.println("Unknown Vehicle Subcategory");
                        break;
                }
                break;
            default:
                System.out.println("Unknown Vehicle Category");
                break;
        }
    }
}

Output:

Vehicle Category: Car

Vehicle Subcategory: Sedan

Sedans are known for their comfortable ride.

Explanation:

  1. public class NestedSwitchExample { : Starts a class named “ NestedSwitchExample “.
  2. public static void main(String[] args) { : The main part of the program begins.
  3. String vehicleCategory = “Car”; : We’re setting the vehicle’s general category as “Car.”
  4. String vehicleSubcategory = “Sedan”; : We’re specifying the specific type of car as “Sedan.
  5. switch (vehicleCategory) { : We’re checking the type of vehicle.
  6. case “Car”: If it’s a car.
    • System.out.println(“Vehicle Category: Car”); : Prints “Vehicle Category: Car “.
    • switch (vehicleSubcategory) { : Now, we’re checking the specific type of car.
    • case “Sedan”: If it’s a Sedan, execute the following:
    • System.out.println(“Vehicle Subcategory: Sedan”); :Print “Vehicle Subcategory: Sedan.”
    • System.out.println(“Sedans are known for their comfortable ride.”); : print “Sedans are known for their comfortable ride.”
    • break; :Exit the inner switch for “Sedan.”
    • case “SUV”: If it’s an SUV, execute the following:
    • System.out.println(“Vehicle Subcategory: SUV”); : Print “Vehicle Subcategory: SUV.”
    • System.out.println(“SUVs are popular for their off-road capability.”); : print “SUVs are popular for their off-road capability.”
    • break;:Exit the inner switch for “SUV.”
    • default: If it’s not Sedan or SUV, execute the following:
    • System.out.println(“Unknown Vehicle Subcategory”); :Print “Unknown Vehicle Subcategory.”
    • break; :Exit the inner switch for default.
    • break; :Exit the outer switch for “Car.”
  7. case “Motorcycle”: If it’s a Motorcycle.
    • out.println(“Vehicle Category: Motorcycle”); – Prints “Vehicle Category: Motorcycle“.
    • switch (vehicleSubcategory) { : Now, we’re checking the specific type of car.
    • case “ Sport”: If it’s a Sport, execute the following:
    • System.out.println(“Vehicle Subcategory: Sport”); :Print “Vehicle Subcategory: Sport.”
    • System.out.println(“Sport motorcycles are built for high-speed performance.”); : print “Sport motorcycles are built for high-speed performance.”
    • break; :Exit the inner switch for ” Sport.”
    • case “ Cruiser”: If it’s an Cruiser, execute the following:
    • System.out.println(“Vehicle Subcategory: Cruiser”); : Print “Vehicle Subcategory: Cruiser.”
    • System.out.println(“Cruisers are designed for relaxed, long rides.”); : print Cruisers are designed for relaxed, long rides.”
    • break;:Exit the inner switch for ” Cruiser.”
    • default: If it’s not Sport or Cruiser, execute the following:
    • System.out.println(“Unknown Vehicle Subcategory”); :Print “Unknown Vehicle Subcategory.”
    • break; :Exit the inner switch for default.
    • break; :Exit the outer switch for “Motorcycle
  8. default: – If none of the above cases match:
    • System.out.println(“Unknown Vehicle Category”); – Prints ” Unknown Vehicle Category”.
    • break; – Stops the switch.
  9. } : Ends the switch.
  10. } : Ends the main method.
  11. } : Ends the class.

In summary, this Java program categorizes and provides information about vehicles based on their category and subcategory using nested switch statements. Messages are printed to the console based on the values of vehicleCategory and vehicleSubcategory.

Visited 1 times, 1 visit(s) today

Comments are closed.

Close