Java for Beginners · Module 4: Control Flow
🎯 When Many Choices Depend on One Value
Suppose a number from 1 to 7 should print a day name. An else-if ladder works, but it repeats the same test again and again. A switch statement is a cleaner way to pick one path based on the value of a single variable.
1️⃣ Classic switch
switch (day)day = 3
case 3:prints Wednesday
break;leave the switch
default. Without break, execution keeps going into the next case.Figure 1: How an old-style switch finds and runs a case.
| Allowed selector types | Not allowed |
byte short char int | long |
String | float double |
enum, wrapper classes (Integer, Character) | boolean |
Figure 4: What a switch can test.
Program 1: Day of the week
public class SwitchBasic {
public static void main(String[] args) {
int day = 3;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
default:
System.out.println("Other day");
}
}
}
Wednesday
- The value of
dayis compared with eachcaselabel. Case 3 matches. breakjumps out of the switch so the following cases do not run.defaultis like the finalelse: it runs when no case matches. It is optional and usually written last.- Each case label must be a constant (a literal or a
finalvariable), and no two labels may be equal.
2️⃣ Fall-Through
If break is missing, Java keeps running the following cases, even if their labels do not match. Sometimes this is useful, and sometimes it is a bug.
| n = 2 | Runs? | Output |
case 1: | skipped (no match) | – |
case 2: | match, starts here | two |
case 3: | falls through | three |
default: | falls through | default |
break, everything from the matching case to the end of the switch runs.Figure 2: Fall-through when break is missing.
public class FallThrough {
public static void main(String[] args) {
int n = 2;
System.out.println("Without break:");
switch (n) {
case 1:
System.out.println("one");
case 2:
System.out.println("two");
case 3:
System.out.println("three");
default:
System.out.println("default");
}
char grade = 'B';
System.out.print("Grade " + grade + " means: ");
switch (grade) {
case 'A':
case 'B':
System.out.println("Good");
break;
case 'C':
System.out.println("Average");
break;
default:
System.out.println("Unknown");
}
}
}
Without break:
two
three
default
Grade B means: Good
- In the first switch, case 2 matches and nothing stops it, so “two”, “three” and “default” all print.
- In the second switch, the empty
case 'A':deliberately falls intocase 'B':, so both grades share one answer. This is the main good use of fall-through. - If you compile the first switch with
javac -Xlint:all, the compiler warns about it: [fallthrough] possible fall-through into case.
3️⃣ switch on Characters and Strings
A switch can test char and String values too. Here is a small calculator.
public class Calc {
public static void main(String[] args) {
double a = 12, b = 4;
char op = '/';
switch (op) {
case '+': System.out.println(a + b); break;
case '-': System.out.println(a - b); break;
case '*': System.out.println(a * b); break;
case '/':
if (b != 0) System.out.println(a / b);
else System.out.println("Cannot divide by zero");
break;
default: System.out.println("Invalid operator");
}
}
}
3.0
- The selector is the
charinop. Only the matching branch runs. - The selector itself cannot be a
double, but the values being calculated can be. - Inside a case you can use any statements, including an
iffrom Lesson 16.
4️⃣ The Modern switch (Java 14 and later)
| Classic switch | Modern switch (Java 14+) | |
| Separator | case 1: | case 1 -> |
| break needed? | Yes, or it falls through | No, never falls through |
| Several values | stacked cases | case 1, 2, 3 -> |
| Gives a value? | No | Yes: int x = switch (...) { ... }; |
Figure 3: Classic switch versus the modern arrow form.
The arrow form removes the need for break, never falls through, and can produce a value directly. Java 21 supports it fully.
public class ModernSwitch {
public static void main(String[] args) {
int month = 2;
int days = switch (month) {
case 1, 3, 5, 7, 8, 10, 12 -> 31;
case 4, 6, 9, 11 -> 30;
case 2 -> 28;
default -> 0;
};
System.out.println("Month " + month + " has " + days + " days");
String cmd = "stop";
switch (cmd) {
case "go" -> System.out.println("Moving");
case "stop" -> System.out.println("Halted");
default -> System.out.println("Unknown command");
}
String size = "M";
String label = switch (size) {
case "S" -> "Small";
case "M" -> {
String t = "Medium";
yield t + " (popular)";
}
default -> "Other";
};
System.out.println(label);
}
}
Month 2 has 28 days
Halted
Medium (popular)
case 1, 3, 5 -> 31lists several values in one case, replacing stacked labels.- The whole
switchis an expression here: its result is stored indays. The expression form must cover every possible value, which is why it has adefault. - When one case needs several statements, wrap them in braces and return the value with
yield. - Use this form if your Java version is 14 or later. Older versions only know the classic form, so you should recognise both.
5️⃣ Errors Beginners Meet
Duplicate case label
public class Dup {
public static void main(String[] args) {
int x = 1;
switch (x) {
case 1: System.out.println("a"); break;
case 1: System.out.println("b"); break;
}
}
}
Dup.java:6: error: duplicate case label
case 1: System.out.println(“b”); break;
^
1 error
A selector type that is not allowed
public class BadType {
public static void main(String[] args) {
double d = 2.0;
switch (d) {
case 2.0: System.out.println("two"); break;
}
}
}
BadType.java:4: error: selector type double is not allowed
switch (d) {
^
1 error
- Decimals cannot be switched on because they are not exact. Use an
ifchain for decimals.
A case label that is not a constant
public class NotConst {
public static void main(String[] args) {
int x = 2, y = 2;
switch (x) {
case y: System.out.println("same"); break;
}
}
}
NotConst.java:5: error: constant expression required
case y: System.out.println(“same”); break;
^
1 error
- A case label must be known at compile time. Make the variable
finalwith a fixed value, or use anif.
⚠️ Common Mistakes
| Mistake | Problem | Fix |
|---|---|---|
Forgetting break | Falls into the next case | Add break, or use the arrow form |
Switching on a double or boolean | Not allowed | Use if-else |
| Duplicate case values | Compile error | Each label once |
Using a range like case 1..5 | No ranges in Java | List values, or use if |
Mixing : and -> in one switch | Not allowed | Pick one style |
| Comparing case text with different capitals | “Stop” does not match “stop” | Convert with toLowerCase() first |
❓ Frequently Asked Questions
Q1. Is default required?
No for a statement, but it is good practice. A switch expression needs it unless every value is covered.
Q2. Does default have to be last?
No, but putting it last is the convention. If it is not last, it still needs a break (in the classic form).
Q3. When should I use switch instead of if?
When comparing one variable against several fixed values. Use if for ranges or complex conditions.
Q4. Can a switch test a String?
Yes, since Java 7. The match is case-sensitive.
✅ Key Takeaways
switchpicks a path by comparing one value to constant case labels.- Allowed selectors: byte, short, char, int, String, enum (not long, float, double, boolean).
- Use
breakto stop fall-through. Stacked cases share code on purpose. defaulthandles values with no matching case.- The modern
case x ->form needs nobreakand can return a value.
🎓 Practice questions: (1) Write a program that prints the name of the month for a number from 1 to 12. (2) Use a switch to tell whether a letter is a vowel or a consonant (stacked cases). (3) Predict the output of the fall-through example if n is 1. (4) Why can a switch not use a double selector? (5) Rewrite the day-of-week program using the arrow form.
All 30 lessons in this series (open course page)
Module 1 · Getting Started
- Lesson 1: What is Java? Features and Uses
- Lesson 2: Installing the JDK and Running Your First Program
- Lesson 3: JDK, JRE, JVM and WORA Explained
- Lesson 4: JVM Architecture and JIT Compilation
- Lesson 5: Hello World Program Explained Line by Line
Module 2 · Building Blocks
- Lesson 6: Comments, Identifiers and Keywords
- Lesson 7: Variables and Literals
- Lesson 8: Primitive Data Types in Java
- Lesson 9: Type Conversion and Casting
- Lesson 10: Taking Input with the Scanner Class
- Lesson 11: Escape Characters and Variable Scope in Java
Module 3 · Operators
- Lesson 12: Arithmetic Operators and Increment/Decrement in Java
- Lesson 13: Relational and Logical Operators in Java
- Lesson 14: Bitwise and Shift Operators in Java
- Lesson 15: Assignment, Ternary Operator and Operator Precedence in Java
Module 4 · Control Flow
- Lesson 16: if, if-else and else-if Ladder in Java
- Lesson 17: switch Statement in Java (Classic and Modern)
- Lesson 18: while and do-while Loops in Java
- Lesson 19: for Loop and Nested Loops (Patterns) in Java
- Lesson 20: break, continue and Labelled Loops in Java
Module 5 · Data and Methods
- Lesson 21: Arrays in Java (One-Dimensional)
- Lesson 22: Multidimensional Arrays in Java
- Lesson 23: Strings and the String Pool in Java
- Lesson 24: String Methods and StringBuilder in Java
- Lesson 25: Methods and Method Overloading in Java
- Lesson 26: Recursion Basics in Java
- Lesson 27: ArrayList and Wrapper Classes in Java
- Lesson 28: Exception Handling Basics in Java