Java: Switch Statement

Profile picture for user arilio666

A switch statement in a java programming language is a fundamental control structure used to perform basic actions based upon different conditions passed within. In a switch case, we pass upon a condition that checks whether the state gets satisfied upon the switch block of its presence.

Syntax

switch(expression)
{
    case val1:
        break;
    case val2:
        break;
    default:
        //statement
}

Example:

public class Test
{
    public static void main(String[] args)
    {
        int day = 2;
        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;
            default:
                System.out.println("Rest Day");
        }
    }
}

Output: Today's Workout Plan: Back And Biceps

Here we used a workout plan switch case statement with a day variable as 2. When the case matches with the passed in expression it'll execute that case and break the statement with that.

I have given 2 expressions in the switch so it will stop at case 2 and execute its statement. The break is optional but without it, the expression case will be chosen by case2 and case3 also will get executed along with that. So whatever follows after the matched case it will get executed without the break.

Like break, there is an optional default keyword which in such case where the expression is not matched with the case and unsatisfied the default switch automatically gets its block executed.

Tags