Print Month Name in Java
beginner· Control Flow · Switch Statement
Problem
Mapping a small fixed set of numbers to names, like 1 through 12 to month names, is exactly the kind of direct lookup a switch statement is built for.
Given a number from 1 to 12, print the matching month name.
Input
month = 7
Output
July
Java Program
Java
public class MonthName {
public static void main(String[] args) {
int month = 7;
String monthName;
switch (month) {
case 1:
monthName = "January";
break;
case 2:
monthName = "February";
break;
case 3:
monthName = "March";
break;
case 4:
monthName = "April";
break;
case 5:
monthName = "May";
break;
case 6:
monthName = "June";
break;
case 7:
monthName = "July";
break;
case 8:
monthName = "August";
break;
case 9:
monthName = "September";
break;
case 10:
monthName = "October";
break;
case 11:
monthName = "November";
break;
case 12:
monthName = "December";
break;
default:
monthName = "Invalid month"; // required so monthName is always assigned
}
System.out.println(monthName);
}
}Output
July
Core Logic
Matching the month number against each case label directly maps it to the corresponding month name.
How It Works
- 1
switch (month)compares the int against case labels1through12. - 2Each case assigns the matching month name to
monthNameandbreaks. - 3The
defaultcase catches any number outside 1-12 and assigns"Invalid month".
For
month = 7, the seventh case matches and assigns "July".💡
Key Point: Twelve cases is a lot to read through, but each one is a flat, direct mapping — there's no shared logic between them worth factoring out, unlike the days-in-month program where the cases group naturally.
Key Concepts
switch statementint case labelsdefault case