Java ProgramsControl FlowSeason Finder Using Switch

Season Finder Using Switch in Java

beginner·  Control Flow  ·  Switch Statement

Problem

Stacking multiple case labels together lets several months fall through to the same season without repeating the assignment.

Given a month number from 1 to 12, determine which season it falls in.

Input
month = 6
Output
Summer

Java Program

Java
public class SeasonFinderSwitch { public static void main(String[] args) { int month = 6; String season; switch (month) { case 12: // stacked labels: Dec, Jan, Feb share one assignment case 1: case 2: season = "Winter"; break; case 3: case 4: case 5: season = "Spring"; break; case 6: case 7: case 8: season = "Summer"; break; case 9: case 10: case 11: season = "Autumn"; break; default: season = "Invalid month"; } System.out.println(season); } }

Output

Summer

Core Logic

Grouping three month numbers under each case, by stacking their labels together, maps every month to its season in one switch.

How It Works
  1. 1switch (month) matches the month number against each stacked group of case labels.
  2. 2Cases 12, 1, and 2 share a single "Winter" assignment, since none of them has its own break in between.
  3. 3Cases 3-5, 6-8, and 9-11 are grouped the same way for Spring, Summer, and Autumn.
  4. 4The default case handles any number outside 1-12, printing "Invalid month".
For month = 6, it falls into the stacked case 6/7/8 group, so "Summer" is printed.
💡

Key Point: Stacking case labels without a break between them is what lets three different month numbers share one assignment — write out an unstacked switch and you'd need three times as many lines.

Key Concepts

switch statementfall-through casescase grouping

Related Programs