Java Switch
Choose one action or one result from a set of named alternatives. Learn to trace classic cases, avoid accidental fall-through, and turn a command into a clear menu response.
Before you start: review if, else if, and else and Scanner input. Examples run in the existing Java 21 sandbox. Predict the output, run the program, then change one value to test your explanation.
What you will be able to do
- Trace a selector to its matching case or default.
- Explain why colon cases can fall through and where break continues.
- Use arrow rules and grouped labels without accidental fall-through.
- Produce a value with a complete switch expression and yield.
- Handle case-sensitive strings, null, and unsupported input deliberately.
- Build and test a one-command menu using Scanner.
One question, several named answers
Imagine a small learning menu: 1 means courses, 2 means practice, and every other number needs an unknown-choice message. All branches compare the same value with specific alternatives. A switch expresses that structure directly instead of repeating choice == 1, choice == 2, and so on in an if/else chain.
The value inside switch (...) is the selector. A case names a possible match. Java evaluates the selector once for that switch execution and finds the applicable label. In the first program, choice is 2, so execution enters case 2. It does not execute the earlier case 1 merely because that label appears first in the source.
Predict the two printed lines before pressing Run. The selected case prints Practice exercises; break exits the switch; the statement after the closing brace prints Menu preview complete. The menu is only a console demonstration: printing a destination does not open a page, enroll a student, or grant access to anything.
Main.java · Follow one matching case
Predict the result, edit Main.java, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
Practice exercises
Menu preview complete.
Walk through choice 2, one step at a time
- Evaluate choice: its value is 2.
- Enter case 2 and print Practice exercises.
- break exits the switch, without ending main.
- Print the shared completion line after the switch.
Now try 1 and 9. Which line changes, and which line stays the same?
break exits the switch; default handles an unmatched value
In this colon-style statement, break stops execution of the selected switch block. It does not end main. That is why the final preview message still prints. return would instead leave the current method, skipping later statements in that method. Keep these two control-flow decisions separate.
Change choice from 2 to 9. Neither numbered case matches, so default prints Unknown choice. Then execution continues after the switch. For this integer switch statement, omitting default is legal: an unmatched value would execute none of its case work. An explicit fallback is usually clearer when a user can supply unsupported values.
Place default last for readability, but do not mistake it for an input validator that catches every possible problem. A missing value or a failed parse must be handled before this integer selector exists. A null String also needs separate attention unless an explicit null case is supplied; an ordinary default does not catch it.
Colon cases can keep running after the matching label
A colon label is an entry point, not a wall around its statements. Without break or another abrupt exit, execution continues into the statements below the next label. In this deliberately unusual example, level 2 enters case 2 and prints Intermediate task, then reaches default and prints Shared task as well.
Notice that default runs here even though a numbered case matched. No new matching decision happened: control simply continued downward. With level 1, all three task lines print. With level 9, execution starts at default and prints only Shared task. Trace the entry point first, then follow statements until an exit.
Fall-through is legal and occasionally intentional, but it is a common menu bug. If each choice should do exactly one action, add breaks to colon cases or prefer arrow rules. If several cases genuinely share work, group their labels explicitly rather than making readers guess whether a missing break was deliberate.
Main.java · Observe deliberate fall-through
Predict the result, edit Main.java, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
Intermediate task
Shared task
Predict levels 1, 2, and 9
Level 1 prints Foundation task, Intermediate task, and Shared task. Level 2 prints only the last two. Level 9 prints only Shared task. Once execution enters a colon case, the next label does not perform another match check.
Arrow rules do not fall through
An arrow rule uses -> instead of a colon. When its label matches, Java executes that rule, then leaves the switch normally. The case 2 block prints two related lines and does not continue into default. You do not need to add break to obtain that no-fall-through behavior.
Use braces when one arrow rule needs several statements. A single printing statement can follow the arrow directly; a block lets you group a short action and declare local variables. Arrow syntax does not mean the whole program stops afterward: the final preview line still runs outside the switch.
Do not mix colon labels and arrow rules within one switch block. Choose one form consistently. You will still encounter colon switches in existing projects, so learn to trace both, but arrow rules are a useful default for new beginner code with independent choices.
Main.java · Arrow rules choose one action
Predict the result, edit Main.java, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
Practice exercises
Try one small problem.
Menu preview complete.
Group alternatives that really mean the same thing
A menu may accept both learn and courses for the same destination. Separate the constant labels with commas before one arrow: the selected action is shared by either spelling. This is an explicit list of accepted alternatives, not a test that both strings must match together.
In the example, courses selects Course roadmap. Change it to ? to select Help guide. The question-mark alias is ordinary string data inside quotes, not a Java operator in this position. The switch does not automatically understand synonyms such as lessons; you must decide which commands your interface supports.
Each constant case label must be compatible with the selector and must not duplicate another case value in the same switch. Labels are not arbitrary changing variables or boolean questions such as score >= 50. Java 21 also has more advanced pattern forms, but this lesson intentionally focuses on constant labels and leaves pattern matching for later.
Main.java · Several labels share an action
Predict the result, edit Main.java, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
Course roadmap
A switch expression answers a question with a value
So far the switch statements chose actions that printed messages. A switch expression instead produces a value for another expression, such as the right-hand side of an assignment. Read String schedule = switch (day) as: choose one schedule string from this day, then assign that result to schedule.
Each arrow here supplies a string, not a println call. After the switch has produced its result, one shared printing statement uses it. The semicolon after the closing brace ends the variable declaration. It is required here even though the earlier standalone switch statements did not need a semicolon after their braces.
A switch expression must be exhaustive: every possible selector value must be covered, or the selected path must throw rather than finish without a value. Listing days 1 through 7 does not cover every int, so default supplies Invalid day. That fallback is part of the example policy; it does not silently turn an invalid number into a valid weekday.
Main.java · A switch can produce one value
Predict the result, edit Main.java, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
Plan: Weekend review
Use yield when an expression arm needs a block
A simple arrow expression such as -> 10 already provides its result. When a case needs local calculations, put them inside braces and use yield to supply the result of that block to the enclosing switch expression. The workshop arm calculates 15 + 25, then yields 40 for the minutes assignment.
yield does not print the result. The shared println after the switch does that. Nor does yield exit main: execution continues after the completed assignment. In contrast, break leaves a switch statement without supplying an expression value, and return leaves the current method. Do not use break 40 or substitute return 40 inside this expression arm.
Every normally completing route through an expression block must supply a compatible result. Delete yield and the block cannot finish as a valid expression arm. Keep calculations small and give intermediate values meaningful names; a long block is a sign that a later methods lesson may offer a clearer way to organize the work.
Main.java · A block yields its result
Predict the result, edit Main.java, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
Duration: 40 minutes
Explain the value without running
workshop selects the block. Its local values are 15 and 25, and yield supplies their sum, 40. That result becomes minutes. The final println formats it. Try quick and then unknown to explain the two other results.
Text matching is exact; normalization is your policy
String case labels compare string contents, not object identity, but the comparison is case-sensitive. HELP is not the same command as help. This program deliberately strips surrounding whitespace and converts text to lowercase before matching. That is a chosen interface rule, not an automatic feature of switch.
Locale.ROOT makes case conversion independent of the computer's default language settings, which is appropriate for these fixed command words. It does not make all international text interchangeable or remove internal spaces. The input help now remains unsupported because our command vocabulary contains help, not arbitrary sentences.
The null guard comes before strip or switch so a missing reference never reaches either operation. In Java 21 you can explicitly write a case null in suitable switches without preview features, but a plain default alone does not match null. We use an early guard here to keep missing-input handling obvious and separate from command matching.
Main.java · Normalize text before matching
Predict the result, edit Main.java, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
Help guide
Use if/else for ranges; switch for discrete alternatives
A score of 78 belongs to a range, not one special constant. if/else directly expresses at least 80, otherwise at least 50, otherwise below 50. Replacing those questions with dozens of individual numeric case labels makes the rule harder to inspect and easier to get wrong.
Use the constant-label switch style from this lesson for specific menu commands, status codes, or known categories. Use if/else for thresholds, independent boolean checks, or conditions involving several unrelated values. Neither structure is automatically faster or better merely because its syntax is shorter; choose the one that states the decision clearly.
For every decision, test more than the original happy path. Try a known first case, another known case, a grouped alias, and an unknown value. For text, also test your stated capitalization, whitespace, blank, and missing-input policy. A compiler can check syntax and exhaustiveness, but it cannot decide whether your selected message is the one students actually need.
Main.java · Keep range checks in if/else
Predict the result, edit Main.java, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
Foundation target met
Repair exercise: stop the extra menu actions
This menu should print only Practice exercises and then Menu preview complete. Run it first: why does it also print Help guide and Unknown choice? Repair the colon-style switch without deleting the other supported choices.
Main.java · Find the missing exits
Predict the result, edit Main.java, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
Reveal the explained repair
The original enters case 2 and keeps executing statements below later labels because no break stops it. Add break after each numbered action. The last default has no following case to fall into. The shared footer stays outside the switch, so it still runs for every choice. Rewriting every case consistently as an arrow rule is another valid repair; replacing break with return would incorrectly skip the footer.
Main.java · Repaired menu
Predict the result, edit Main.java, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
Practice exercises
Menu preview complete.
Retest choices 1, 3, and 9. Every choice should print exactly one menu result followed by the same footer.
Independent lab: route one learning command
Build a one-command learning menu. Read exactly one input line, normalize it, then print the matching destination. This is a console preview, not real site navigation or account access. There is no repeating menu yet; loops are the next topic.
- If no input line exists, print No command supplied. and return.
- Strip surrounding whitespace and lowercase with Locale.ROOT. If the result is empty, print Command cannot be blank. and return.
- Accept learn or courses for Course roadmap; practice for Practice exercises; help or ? for Help guide.
- For quit, print Goodbye. and return without a destination or completion footer.
- For any unsupported command, print Unknown command. Use learn, practice, help, or quit. and return without a completion footer.
- For a recognized destination, print Choice: followed by the normalized command, Destination: followed by the destination, and Menu preview complete. Use grouped arrow labels in a switch.
The runner starts with PRACTICE surrounded by spaces on one input line. Input is supplied before execution, not typed into a live terminal. Expected output:
Choice: practice
Destination: Practice exercises
Menu preview complete.
Main.java · Build your learning menu
Predict the result, edit Main.java, then run your program.
Standard input · prefilled example
Select Run code to compile and execute this program.
Hints before the solution
Check hasNextLine before reading. Normalize once, then check for blank text. Declare destination outside the switch; recognized rules assign it, while quit and unknown rules return. Print the shared three-line result only after that decision. Arrow rules with multiple statements need braces.
Reveal the explained lab solution
Main.java · Learning-menu solution
Predict the result, edit Main.java, then run your program.
Standard input · prefilled example
Select Run code to compile and execute this program.
hasNextLine distinguishes missing input from a supplied blank line. Normalization happens once, before the decision. Each recognized destination assigns the same outer variable; quit and default return instead. Every path that reaches the shared output therefore has an assigned destination. Arrow rules cannot fall through. return, not an ordinary switch break, prevents rejected commands from reaching the success footer. This uses a switch statement because two cases intentionally finish the method rather than produce a value.
Test changes and boundaries
Run each test by editing the input box. Reset restores the original source and prefilled practice command. A working happy path is not enough: rejected paths must avoid the destination and completion messages.
- Try learn, courses, practice, help, and ?. Each must produce exactly one correct destination and one footer.
- Try surrounding spaces and uppercase text, such as two spaces followed by HELP. The printed choice must be normalized.
- Try quit: only Goodbye. should print. Try delete: only the unknown-command message should print.
- Clear the input entirely for No command supplied. Enter one blank line or spaces for Command cannot be blank. These are distinct cases.
- Supply learn on the first line and quit on the second. Only learn is processed. This program reads one command, not a repeating interactive session.
Common mistakes and how to diagnose them
Several menu actions run
Inspect colon cases for missing break statements. Once a label is entered, later labels do not stop execution. Add the intended exits or use consistent arrow rules; do not remove supported menu options to hide the symptom.
A block does not supply an expression result
An arrow expression block needs yield on each normally completing path. Printing a number does not yield it. A switch expression also needs exhaustive coverage; for an int or String menu, an explicit default is usually the simplest fallback.
The footer is unexpectedly skipped
return exits the current method, while break leaves the switch statement and continues afterward. Decide whether a path should stop the method or merely finish its selection. In the lab only recognized destinations reach the footer.
An apparently valid word reaches default
String matching is case-sensitive and preserves whitespace unless you explicitly normalize it. Inspect the exact input. Strip and use Locale.ROOT lowercasing only when that agrees with your chosen command policy.
A missing String causes NullPointerException
A regular default does not handle a null selector, and calling strip on null fails even earlier. Check for null first when your data source can return it. The Scanner lab checks line availability before reading instead.
The compiler rejects a case label or arrow
Check duplicate constants, incompatible labels, mixed colon and arrow forms, and the Java version. Arrow switches and switch expressions are standard in Java 14 and newer; this course runs Java 21. A range such as case score >= 50 is not a constant case label.
Frequently asked questions
Do arrow cases need break?
No. Arrow rules do not fall through into the following rule. After the selected action completes normally, a switch statement finishes and execution continues after it.
Is default always required?
Not for the basic int or String switch statements shown here, but a switch expression must be exhaustive. Other enhanced forms have their own coverage requirements. Explicitly handle unsupported user commands instead of relying on silent no-op behavior.
Can I switch on a String?
Yes. Constant String labels match contents case-sensitively. Normalize only if your interface promises that policy. An ordinary default does not match null; guard it or use an explicit Java 21 null case where appropriate.
What is the difference between break, yield, and return?
In this lesson, break leaves a switch statement, yield supplies a switch expression result, and return leaves the current method. They are not interchangeable ways of saying that a case has finished.
Which selector types should beginners use?
These examples use int and String. Traditional constant switches also support char, byte, short, their wrappers, and enum values. Java 21 additionally supports pattern matching over reference types, which is beyond this lesson. Do not infer that boolean, long, float, or double numeric switches work like these examples in Java 21.
Choose the match, then explain how it exits
A selector identifies the value being classified. A case names a supported alternative. Colon switches need deliberate exits; arrow rules do not fall through. A switch expression produces a result and must be exhaustive, with yield supplying a result from a block.
Before moving on, explain why an unmatched command is different from missing input, why default alone does not catch null, and why the lab uses return for quit. Next: while and do-while loops, where you will learn how to repeat work rather than reading just one command.
Can you trace the selected case?
Answer all six questions and read the explanations. Results are temporary on this page and do not save course progress.
References and related learning
The scenarios, explanations, examples, and exercises are original SovranCode material. Official Java 21 references support the language rules.
- Java 21 specification: switch statements
- Java 21 specification: switch expressions
- Oracle Java 21 language guide: switch expressions
Review if/else decisions · Review Scanner input · Review String operations · Java course roadmap.
Last updated: