Find Number of Days in Month in Java
Problem
Most months have a fixed day count, but February's depends on whether the given year is a leap year, so the month lookup has to fold in that one extra check.
Given a month and a year, find how many days that month has.
Java Program
public class DaysInMonth {
public static void main(String[] args) {
int month = 2;
int year = 2024;
int days;
switch (month) {
case 1: case 3: case 5: case 7: case 8: case 10: case 12: // 31-day months
days = 31;
break;
case 4: case 6: case 9: case 11: // 30-day months
days = 30;
break;
case 2: {
boolean isLeap = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
days = isLeap ? 29 : 28;
break;
}
default:
days = 0; // invalid month
}
System.out.println("Days in month: " + days);
}
}Output
Core Logic
Grouping the months that share the same day count under stacked case labels, and handling February on its own, covers every month with far fewer branches than twelve separate cases.
- 1
case 1: case 3: case 5: case 7: case 8: case 10: case 12:stacks every 31-day month under one assignment. - 2
case 4: case 6: case 9: case 11:stacks every 30-day month the same way. - 3
case 2applies the standard leap-year rule — divisible by 4, except century years unless also divisible by 400 — to decide between 28 and 29. - 4The
defaultcase handles an invalid month number with0.
month = 2 and year = 2024, the leap-year check passes, so days becomes 29.Key Point: Stacking case labels only works because the grouped months genuinely share identical logic — February needs its own case precisely because it doesn't.
Key Concepts
Approach 2: Using an Array Lookup
public class DaysInMonthArrayLookup {
public static void main(String[] args) {
int month = 2;
int year = 2024;
int[] daysInMonth = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; // index 0 = January
int days = daysInMonth[month - 1];
boolean isLeap = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
if (month == 2 && isLeap) {
days = 29;
}
System.out.println("Days in month: " + days);
}
}
Output
Core Logic
A fixed array of day counts, indexed by month, replaces the whole case list with a single lookup, then February gets adjusted afterward if needed.
- 1
daysInMonthholds the standard day count for each month, with index0for January. - 2
daysInMonth[month - 1]looks up the count directly, since months are 1-indexed but arrays aren't. - 3The same leap-year check runs afterward, and overwrites
daysto29only whenmonth == 2and the year qualifies.
month = 2, the lookup returns the array's default of 28, then the leap-year check overwrites it to 29.Key Point: This trades the switch's explicit case-by-case grouping for a compact data table — a good fit once the mapping is large enough that writing out every case starts to feel repetitive.