CodeBlanks Logo Icon CodeBlanks

switch

Learn multi-way selection with switch, case, break and default.

switch

To check many values of a variable in order you use switch. In switch (day) { case "Mon": ...; break; default: ...; } the matching case runs based on the value of day.

switch is a more readable form of many else ifs. case values must be constants; they cannot be variables. If no case matches default runs; default is optional but a good habit.

break and default

At the end of each case block break; exits the switch; otherwise Dart gives an error. break is a separate concept; you will see more about it with loops in the next section. For now know it exits the switch.

The default block runs when no case matches. It is the switch equivalent of else. default is usually written last but is not required. Practical tip: give every switch a default to catch unexpected values.

Practice Day name with switch

Declare a String variable day with the value "Mon". With switch (day): in the case "Mon": block print print("Monday"); and exit with break;. In the default: block print print("Unknown");. The output on a single line must be Monday.

Starter code

main.dart
// Declare day, switch Mon to Monday and print it

Sample solution

main.dart
String day = "Mon";
switch (day) {
  case "Mon":
    print("Monday");
    break;
  default:
    print("Unknown");
}

Expected output

Monday

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match each part to its job

Term Meaning
switch (x) Variable to check
case A: A value match
default: When none match
break; Exits the switch

2 Write the case line

Question
String day = "Mon";
switch (day) {
  case ____:
    print("Monday");
    break;
  default:
    print("Unknown");
}
Answer
String day = "Mon";
switch (day) {
  case "Mon":
    print("Monday");
    break;
  default:
    print("Unknown");
}

Explanation: case "Mon": is the form; no parentheses, square or curly brackets needed.

3 What runs if no case matches in a switch?

main.dart
switch (x) {
  case 1: ...; break;
  default: ...;
}
  • the default block Correct answer
  • The program crashes
  • The first case runs again
  • Nothing at all

Explanation: The default block runs when no case matches.

All lessons in Beginner