Nearby lessons
20 of 125Java - switch Statement
📌 What You Will Learn
- The small building blocks of Java: tokens
- All 8 primitive data types with their ranges
- Type casting — implicit and explicit
- Control statements: if, switch, loops
- Arrays — single, double and jagged
- Variable length arguments (var-args)
switch Statement is a core concept of the Java language. This lesson explains switch and switch — The Complete Rules with complete, runnable code examples, clear step-by-step explanations, and common mistakes to avoid with exam-style MCQs at the end.
switch
When you have many fixed values to check, switch is cleaner than many if-else. It selects one case from many.
Example01
switch
Trainer's Note: Updated knowledge: In Java 7+, switch supports String values. From Java 14, a modern switch expression lets you write int x = switch(day) { case 1 -> 100; default -> 0; }; — we will study this in the Java 12-14 chapters. Also, break is needed in old-style switch to stop falling into the next case.
Example02
switch — The Complete Rules
switch is perfect for menu-driven programs (like a stack menu: PUSH, POP, PEEK, EXIT). These are the rules from the classic material:
- Allowed parameter types: byte, short, int, char (and String since Java 7). long, float and double are not allowed.
- All case values must be constants (including final variables) — ordinary variables are not allowed.
- Case values must lie within the range of the switch's data type. For byte b, case 128 is an error.
- Duplicate case values are not allowed.
- default is optional and can be written anywhere, but convention puts it last.
Example03
📝 Key Takeaways
- Tokens are the smallest pieces of a program: identifiers, literals, keywords, operators, separators.
- Java has 8 primitive types: byte, short, int, long, float, double, char, boolean.
- Widening casting is automatic and safe; narrowing casting needs brackets and may lose data.
- if / switch decide which path runs; for / while / do-while repeat code; break and continue control loops.
- Arrays hold many same-type values; index starts at 0; size is fixed; for-each loop reads them simply.
- Var-args (int... x) lets a method take any number of arguments.
🧠 Test Your Knowledge
1 QuestionsProgress: 0 / 1