Command Palette

Search for a command to run...

Back to the lesson: Topic 2.3 — The switch Statement
Core Java · Example 1 of 4

Day names with break

A switch statement compares one value against a list of constant case labels and jumps straight to the matching one. In the classic colon form, execution falls through into the following cases until a break, which is both its trick and its most common bug.

Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write a switch that converts a month number (1–12) to the number of days in it, for a non-leap year, grouping months that share a length.

02

Write a calculator: given char op and two ints, use a switch to print the result for +, -, * and /, and Unknown operator otherwise. Test with '*', '/' and '%' on 12 and 4.

03

Using an enum Size { SMALL, MEDIUM, LARGE } and a switch, print the price of a coffee: 2, 3 and 4 respectively, for all three sizes.

Explain it without notes

01

What is fall-through in a switch statement, and when is it useful?

02

Which types can a classic switch statement select on, and why can't it use long?

03

What happens when a switch's String selector is null?

04

How does the JVM execute a switch on int, and how does a String switch work?

Day names with break
Sign in to run this example in your browser.

Expected output

1 -> Monday
3 -> Wednesday
9 -> unknown