Understanding the Switch Statement in Java

Introduction

The switch statement in Java allows you to execute one out of multiple possible blocks of code based on the value of a given expression. It is often used to simplify complex if-else conditions.

Syntax of the Switch Statement


switch (expression) {
  case value1:
    // code to be executed if expression == value1
    break;
  case value2:
    // code to be executed if expression == value2
    break;
  // more cases...
  default:
    // code to be executed if expression doesn't match any case
}
      

Key Points:

Examples of the Switch Statement

1. Basic Example


int day = 3;
String dayName;
switch (day) {
  case 1:
    dayName = "Monday";
    break;
  case 2:
    dayName = "Tuesday";
    break;
  case 3:
    dayName = "Wednesday";
    break;
  case 4:
    dayName = "Thursday";
    break;
  case 5:
    dayName = "Friday";
    break;
  case 6:
    dayName = "Saturday";
    break;
  case 7:
    dayName = "Sunday";
    break;
  default:
    dayName = "Invalid day";
}
System.out.println(dayName);
      

Output:

Wednesday

Unsolved Problems

  1. Write a program that uses a switch statement to determine the name of the day of the week based on an input number (1-7).
  2. Write a program that calculates the month of the year based on the user's input number (1-12).
  3. Write a program to determine if a given year is a leap year using a switch statement.
  4. Write a program to calculate the number of days in a month (taking into account leap years) using a switch statement.
  5. Write a program that uses a switch statement to print different messages based on the user's input age group (child, teenager, adult, senior).