Java ProgramsControl FlowPrint Day of Week

Print Day of Week in Java

beginner·  Control Flow  ·  Switch Statement

Problem

Mapping a small fixed set of numbers to names, like 1 through 7 to weekday names, is exactly the kind of direct lookup a switch statement is built for.

Given a number from 1 to 7, print the matching day of the week.

Input
day = 3
Output
Wednesday

Java Program

Java
public class DayOfWeek { public static void main(String[] args) { 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"; // required so dayName is always assigned } System.out.println(dayName); } }

Output

Wednesday

Core Logic

Matching the day number against each case label directly maps it to the corresponding day name.

How It Works
  1. 1switch (day) compares the int against case labels 1 through 7.
  2. 2Each case assigns the matching day name to dayName and breaks.
  3. 3The default case catches any number outside 1-7 and assigns "Invalid day".
For day = 3, the third case matches and assigns "Wednesday".
💡

Key Point: The default case matters here specifically because the input is an arbitrary int — without it, a value like 0 or 8 would leave dayName unassigned and fail to compile.

Key Concepts

switch statementint case labelsdefault case

Related Programs