Java
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Object-Oriented Java
-
Section 4: Collections Framework
-
Section 5: Exception Handling
-
Section 6: Generics
-
Section 7: Functional Java
-
Section 8: Concurrency
-
Section 9: I/O and NIO
-
Section 10: JVM Internals
-
Section 11: Modern Java Features
-
Section 12: Build Tools and Project Structure
-
Section 13: Testing
-
Section 14: Databases and Persistence
-
Section 15: Networking
-
Section 16: Design and Best Practices
-
Section 17: Reflection and Annotations
-
Section 18: Logging and Diagnostics
-
Section 19: Date, Time, and Internationalization
-
Section 20: Java Platform Module System
-
Section 21: Security in Java
-
Section 22: Advanced Collections and Data Structures
-
Section 23: More Concurrency Patterns
-
Section 24: Compression, Files, and System Integration
-
Section 25: GUI Programming
-
Section 26: Practical Projects
-
Section 27: Data Structures and Algorithms
-
Section 28: Interview and Algorithm Practice
-
Section 29: JSON and Data Interchange
-
Section 30: More Concurrency Utilities
-
Section 31: More Collections and Streams Practice
-
Section 32: More File and System Programming
-
Section 33: Standard Library Deep Dive
-
Section 34: More Practice and Drills
-
Section 35: More Testing and Quality
-
Section 36: More Design Patterns and Architecture
-
Section 37: Career and Ecosystem
-
Section 38: More OOP and Architecture Practice
-
Section 39: More Enterprise Concepts
-
Section 40: Advanced JavaFX
-
Section 41: More Interview Practice
13: Control Flow: Switch Statements
Imagine you're standing in front of a vending machine. You don't look at every single item in the machine and ask yourself, "Is this a bag of chips? No. Is this a granola bar? No. Is this a soda? Yes!" That would be an incredibly slow way to get a snack. Instead, you just punch in a code—say, B4—and the machine jumps directly to that specific slot to dispense your item.
That's exactly what a switch statement does for your code. While an if-else if chain is like checking every item one by one, a switch is like the vending machine. It takes one value and jumps straight to the "case" that matches it. It's cleaner, faster to read, and tells anyone looking at your code: "I am picking one option from a predefined list."
Choosing the right path
Let's look at a practical example. Suppose you're building a basic customer support menu for a phone system. You want to route the caller based on the number they press.
int userChoice = 2;
switch (userChoice) {
case 1:
System.out.println("Routing to Sales...");
break;
case 2:
System.out.println("Routing to Technical Support...");
break;
case 3:
System.out.println("Routing to Billing...");
break;
default:
System.out.println("Invalid choice. Please try again.");
break;
}
Here is how the vending machine analogy maps to this code:
- The Code (userChoice): This is the button the user pressed. It's the single value the switch is evaluating.
- The Cases (case 1, 2, 3): These are the slots in the machine. If
userChoiceis 2, Java skips cases 1 and jumps straight to case 2. - The Default: This is the "Invalid Entry" light on the machine. If the user presses 9, but you only have 3 options, the
defaultblock catches everything else.
The "Fall-Through" Trap
I have to warn you about the break statement. In the example above, break tells Java, "Okay, we're done here; jump out of the switch entirely." If you forget it, Java does something called "falling through." It will keep executing the code in the next case, regardless of whether the value matches, until it hits a break or the end of the statement.
Usually, falling through is a bug that will keep you up until 2 AM wondering why your "Sales" call is also triggering "Technical Support" and "Billing" messages. However, you can actually use this on purpose if multiple inputs should trigger the same result:
String day = "Saturday";
switch (day) {
case "Monday":
case "Tuesday":
case "Wednesday":
case "Thursday":
case "Friday":
System.out.println("It's a workday.");
break;
case "Saturday":
case "Sunday":
System.out.println("It's the weekend!");
break;
}
Modernizing with Switch Expressions
If you're using a recent version of Java (Java 12 or later), you'll see a much sleeker syntax using arrows (->). I personally prefer this because it eliminates the need for break entirely—no more fall-through bugs. It can even return a value directly into a variable.
String day = "Monday";
String typeOfDay = switch (day) {
case "Monday", "Tuesday", "Wednesday", "Thursday", "Friday" -> "Workday";
case "Saturday", "Sunday" -> "Weekend";
default -> "Unknown day";
};
System.out.println(typeOfDay);
Notice the comma-separated lists and the lack of break. It's concise, readable, and much harder to mess up. When you're writing your own code, use this version if your project environment allows it.
📋 Practical Task
Build a Simple ATM Menu Handler
Your task is to create a program that simulates a basic ATM interface. The program should take an integer input representing a user's menu choice and print the corresponding action.
Requirements:
- Create an integer variable named
menuChoice. - Implement a
switchstatement (either the traditional version or the modern expression version) that handles the following:1: Print "Checking Balance..."2: Print "Depositing Funds..."3: Print "Withdrawing Funds..."4: Print "Changing PIN..."- Any other number: Print "Error: Selection not recognized."
- Ensure that if the user selects
1, it does not also print the messages for2,3, or4.
There are no comments for now.