Java Tutorial Series: This lesson is part of our comprehensive Complete Java Tutorial: Learn Java from Beginner to Advanced.
Switch Statement in Java: Syntax, Cases, Expressions and Use Cases
What Is the switch Statement?
switch selects behavior based on the value of an expression. It is especially useful for discrete choices such as menu options, commands, days and status values.
Traditional switch Syntax
int day = 2;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
default:
System.out.println("Unknown");
}
case and default
Each case represents a possible value. default provides a fallback when no case matches. A default branch is optional but useful when unexpected values need handling.
Why break Matters
In traditional switch statements, break stops execution from continuing into later cases. Without it, Java can fall through to subsequent cases. Intentional fall-through exists, but accidental fall-through is a common error.
Multiple Cases for One Result
Several case labels can lead to the same block when they represent the same behavior, such as Saturday and Sunday both being treated as weekend days.
Switch with Strings
String command = "start";
switch (command) {
case "start":
System.out.println("Starting");
break;
case "stop":
System.out.println("Stopping");
break;
default:
System.out.println("Unknown command");
}
Modern Switch Expressions
Modern Java supports switch expressions that produce values. Arrow-style cases make it easier to express a direct mapping from an input to a result.
int code = 2;
String message = switch (code) {
case 1 -> "Created";
case 2 -> "Updated";
default -> "Unknown";
};
yield
When a switch expression needs multiple statements in a block, yield can provide the value produced by that branch.
switch vs if-else
Use switch for discrete alternatives. Use if-else or else-if when conditions involve ranges, compound boolean logic or relationships between multiple variables.
Practical Menu Example
int option = 3;
switch (option) {
case 1 -> System.out.println("Create account");
case 2 -> System.out.println("View account");
case 3 -> System.out.println("Exit");
default -> System.out.println("Invalid option");
}
Common Mistakes
Watch for missing break in traditional syntax, duplicate case labels, an unsuitable expression, missing default handling and mixing statement-style and expression-style expectations.
Testing switch Logic
Test every intended case and at least one unexpected value. For String cases, test exact expected values and consider how input is normalized before comparison.
Best Practices
Keep each case focused, avoid putting large business processes directly inside a switch, use modern syntax when appropriate and move complex work into methods.
Practice Problems
Create switch programs for weekdays, calculator operations, menu selections, traffic-light states, application commands and simple status handling.
Frequently Asked Questions
What is switch used for? Discrete choices.
What is default? The fallback case.
Why use break? To prevent traditional fall-through.
Can switch produce a value? Yes, with switch expressions.
Conclusion
switch provides a clear structure for discrete choices. Understanding traditional cases, fall-through and modern switch expressions makes this control-flow tool practical for both beginner programs and real applications.
Learn More
- Java Syntax
- Java Variables
- Java Data Types
- Java Operators
- Java Input and Output
- Java Methods
- Java Arrays and Collections
Continue Learning Java
After this topic, continue through the Java control-flow path by practicing the next related statement or loop. Build small programs rather than only reading examples.
Deeper Practical Coverage
Traditional Colon Syntax vs Arrow Rules
Java supports traditional switch labels using case value: and newer switch rules using case value ->. Traditional syntax can fall through when break is omitted. Arrow rules select one rule and do not fall through to the next rule.
For modern projects, arrow syntax is often easier to read when each case has an independent action.
switch (status) {
case "NEW" -> startReview();
case "APPROVED" -> processOrder();
case "REJECTED" -> closeRequest();
default -> handleUnknown();
}
Switch Expressions as Value Producers
A switch expression can directly produce a value.
int day = 3;
String name = switch (day) {
case 1 -> "Monday";
case 2 -> "Tuesday";
case 3 -> "Wednesday";
default -> "Unknown";
};
This is useful when a program needs to transform one discrete state into another value. It can eliminate a temporary variable plus a traditional switch assignment pattern.
Using yield for Multi-Step Cases
When a switch expression needs multiple statements inside a case, a block can be used with yield.
int score = 87;
String result = switch (score / 10) {
case 10, 9 -> "Excellent";
case 8 -> {
if (score >= 85) {
yield "Very good";
}
yield "Good";
}
default -> "Keep practicing";
};
yield returns the value for that switch expression case.
Enums with Switch
Enums are particularly useful when a domain has a fixed set of states. They make the code more explicit than arbitrary strings.
enum OrderStatus {
NEW, PAID, SHIPPED, CANCELLED
}
OrderStatus status = OrderStatus.PAID;
switch (status) {
case NEW -> System.out.println("Awaiting payment");
case PAID -> System.out.println("Prepare order");
case SHIPPED -> System.out.println("In transit");
case CANCELLED -> System.out.println("Order closed");
}
This style appears frequently in domain-oriented Java code.
Modern Java Version Awareness
Switch has evolved considerably across Java releases. Basic switch syntax is long-established, while switch expressions and newer pattern-oriented capabilities belong to more recent Java language versions. Before using a feature, verify the project's source level and runtime environment.
A tutorial should teach both the concept and the compatibility question: code that compiles under one Java release may require changes under another.
Pattern Matching with Switch
Modern Java also provides pattern-oriented switch capabilities. These can make decisions based on object types and patterns rather than only exact constant values. This is an advanced extension of switch and should be learned after ordinary switch statements and expressions are comfortable.
Switch and Business State Machines
Switch is often useful for small state machines where an object has a finite set of states. For larger workflows, avoid putting entire business processes into one switch. Use the switch to route to focused methods or handlers when each state has substantial behavior.
Extended Practice Set
- Create a menu using switch.
- Create an enum-based status processor.
- Convert a traditional switch to arrow rules.
- Write a switch expression returning a value.
- Demonstrate and fix accidental fall-through.
Java Language and Version Note
The Java platform documentation groups control flow into decision-making, looping, and branching constructs. Modern Java has also expanded switch with expression forms, arrow rules, and pattern-oriented capabilities. When publishing this article, the website should state the Java version when an example depends on a newer language feature. Core syntax such as if, if-else, for, while, do-while, break, continue, and traditional switch remains foundational, while newer forms should be presented as version-aware additions.