🎯 What you will learn
Every real application branches: "if the credit score is high, offer a better rate; if it's low, reject." Java gives you two main tools — if/else chains for boolean conditions and switch expressions for matching a single value against multiple cases. Java 14 dramatically improved switch with arrow syntax that eliminates fall-through bugs.
Old switch vs new switch expression:
Old: switch (x) { case A: ...; break; } — fall-through if you forget break
New: switch (x) { case A -> ...; } — no fall-through, returns a value, compiler-exhaustive
🔀 if / else if / else
The classic branching construct. Conditions are evaluated top-to-bottom — the first true branch executes and the rest are skipped. Order matters: always put the most specific condition first.
⚡ Switch expressions (Java 14+)
Switch expressions use arrow syntax — no break needed, no fall-through risk. The whole switch evaluates to a value you can assign directly. The compiler also ensures the switch is exhaustive — missing a case is a compile error for enums and sealed types.
📱 Real-world scenario
Wanjiku is a backend engineer at BoraPay in Nairobi. BoraPay's transaction review rules require different SLA windows based on amount bands. She uses a switch expression with a yield block to handle complex logic inside one of the branches.
yield explained: When a switch arm needs multiple statements (a block), use yield to return the value. yield is to switch expressions what return is to methods — it exits the block with a value.
📊 if/else vs switch — when to use which
| Situation | Use | Why |
|---|---|---|
Range checks (>=750, <700) | if/else | Switch can't match ranges |
| Exact value matching (String, int, enum) | switch expression | Cleaner, exhaustive, no fall-through |
Complex conditions with && / || | if/else | Switch only tests equality |
| Single value → multiple outcomes | switch expression | Returns a value directly |
| 3+ branches on same variable | switch expression | More readable than if/else chain |
🧩 Mini challenge
Write an if/else chain that prints the Indian income tax for a given annual income. Slabs (new regime FY24): 0–3L = 0%, 3–6L = 5%, 6–9L = 10%, 9–12L = 15%, above 12L = 20%. Test with ₹7,50,000.
Write a switch expression that maps a country code ("IN", "KE", "NG", "US") to its currency symbol (₹, KSh, ₦, $). Throw an exception for unknown codes. Test all four.
Rewrite the credit-tier if/else chain in IfElse.java as a switch expression. Hint: you cannot switch on ranges directly — but you can use integer division: creditScore / 50 groups scores into bands.
🎤 Interview Q&A
In the old switch statement, if you omit break at the end of a case, execution continues into the next case — this is called fall-through. Example: case "UPI": fee = 0; without a break will also execute the case "NEFT" body. It is dangerous because it is easy to forget the break and introduce silent bugs that are hard to debug. Java 14's switch expressions with arrow syntax eliminate this — each arrow arm is a single expression or block with no fall-through.
Yes — that is the main point of switch expressions vs switch statements. You can write double fee = switch (method) { case "UPI" -> 0.0; ... }; and the switch evaluates to a value that is assigned directly. For arms that need multiple statements, use a block with yield value; to produce the result. This makes the code more functional and eliminates the need for a temporary variable.
In Java 21 you can switch on: byte, short, char, int (and their wrappers), String, and enum types — these have been available since Java 7. Java 21 adds pattern matching for switch (finalised): you can switch on any object type using type patterns (case Integer i ->, case String s when s.length() > 5 ->). You still cannot switch on long, double, or float.
Use if/else when: (1) you need to check ranges (score >= 700) — switch only tests equality; (2) your conditions involve compound boolean expressions with && or ||; (3) you are branching on the result of a method call with complex logic. Switch expressions shine when you have a single value with many exact-match cases — they are more readable and the compiler enforces exhaustiveness.
A switch expression is exhaustive if the compiler can prove it covers all possible input values. For String and int, a default arm makes it exhaustive. For sealed classes and enums, the compiler checks that all subtypes/constants are covered — you don't need default. This matters because a non-exhaustive switch expression could fail to produce a value at runtime, which would be a programming error. The compile-time check converts that potential runtime bug into a compile error — exactly what you want from a type-safe language.
📝 Quiz — 5 questions
yield do?->) in switch expressions solve?int score = 685, which branch executes in the IfElse example above?Next: loops — for, while, do-while →
⚠️ Common mistakes
break in the old switch statement, execution falls through to the next case. This is a silent bug. Use switch expressions with arrow syntax instead — fall-through is impossible.if (score >= 650) before if (score >= 750), everyone with score ≥ 750 hits the SILVER branch instead of PLATINUM. Always put the most restrictive condition first.String and int switches, omitting default in a switch expression is a compile error — the compiler cannot prove exhaustiveness. Always add a default arm or throw an exception.score >= 700 — it only matches exact values. For range-based branching, use if/else. Trying to use switch for ranges is a sign you picked the wrong tool.✅ Key takeaways
- if/else evaluates boolean conditions — use it for ranges, compound conditions, and null checks.
- Switch expressions (Java 14+) match a single value — use them for exact-value dispatch on String, int, or enum.
- Arrow syntax (
->) eliminates fall-through entirely — nobreakneeded. - Multiple values can share one arm:
case "SAT", "SUN" -> "HOLIDAY". - Use
yieldto return a value from a multi-statement switch block arm. - Switch expressions are exhaustive — the compiler rejects missing cases at compile time.
From control flow to production Spring Boot
Join the Best AI Programs — three 5-month courses, fully online, with placement assistance. Week 1 is free.
Explore our AI-era courses →