Java: Nested switch case

Profile picture for user arilio666

The nested switch can be used as an inner switch case within the outer switch case and can be called with the switch statement. This won't be of any trouble to the outer switch because of an inner switch. Since it defines its switch block.

Syntax

Switch(exp)
{
    case 1:
    case 2:
        switch(exp)
        {
            case 3:
            case 4:
        }
}

Example

public class Test
{
    public static void main(String[] args)
    {
        int day = 4;
        String coreWorkout = "Abs And Cardio";
        String workoutPlan;

        switch(day)
        {
            case 1:
                workoutPlan = "Chest And Triceps";
                System.out.println("Today's Workout Plan: " +workoutPlan);
                break;
            case 2:
                workoutPlan = "Back And Biceps";
                System.out.println("Today's Workout Plan: " +workoutPlan);
                break;
            case 3:
                workoutPlan = "Shoulder And legs";
                System.out.println("Today's Workout Plan: " +workoutPlan);
                break;
            case 4:
                switch(coreWorkout)
                {
                    case "Cardio":
                        System.out.println("Cardio Day");
                        break;
                    case "Abs And Cardio":
                        System.out.println("Today's Workout Plan: " +coreWorkout);
                        break;
                    default:
                        System.out.println("Rest Day");
                }
        }
    }
}

Output: Today's Workout Plan: Abs And Cardio

Here we can use another expression and pass inside a case with another inner switch statement which will be executed once the case matches with the respective expression.

Tags