DEV Community

Kesavarthini
Kesavarthini

Posted on

📅 Day of the Week Program in Java Using Switch Case

🔹 Introduction

In Java programming, decision-making statements play a crucial role in controlling the flow of execution. One such statement is the switch case, which is used when we need to execute different code blocks based on a single value.

In this blog, we will learn how to write a Java program to display the day of the week based on a number entered by the user using a switch case.

🔹 Problem Statement

Write a Java program that:
• Takes a number from 1 to 7 as input
• Displays the corresponding day of the week

Mapping:
• 1 → Monday
• 2 → Tuesday
• 3 → Wednesday
• 4 → Thursday
• 5 → Friday
• 6 → Saturday
• 7 → Sunday

If the user enters any other number, the program should display an invalid input message.

🔹 Why Use Switch Case?

• It improves readability when handling multiple conditions
• It is more structured and cleaner than multiple if-else statements
• Best suited when comparing a single variable with fixed values
Enter fullscreen mode Exit fullscreen mode

🔹 Java Program: Day of the Week Using Switch Case

import java.util.Scanner;
public class DayOfWeek {

    public static void main(String[] args) {
        System.out.println("Enter a number(1-7):");
        Scanner scan = new Scanner(System.in);
        int day = scan.nextInt();
        switch(day) {
        case 1:
            System.out.println("Monday");
            break;
        case 2:
            System.out.println("Tuesday");
            break;
        case 3:
            System.out.println("Wednesday");
            break;
        case 4:
            System.out.println("Thursday");
            break;
        case 5:
            System.out.println("Friday");
            break;
        case 6:
            System.out.println("Saturday");
            break;
        case 7:
            System.out.println("Sunday");
            break;
        default:
            System.out.println("Invalid input");

        }
    }

}
Enter fullscreen mode Exit fullscreen mode

🔹 Sample Input and Output

Input:

Enter a number (1-7): 3
Enter fullscreen mode Exit fullscreen mode

Output:

Wednesday
Enter fullscreen mode Exit fullscreen mode

🔹 Explanation

• Scanner class is used to get input from the user
• The switch statement checks the value of day
• Each case represents a day of the week
• break stops execution after the matched case
• default handles invalid inputs
Enter fullscreen mode Exit fullscreen mode

Top comments (0)