🎯 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

💼 Interview reality: "What is the switch expression vs switch statement?" and "What is fall-through in switch?" are standard Java interview questions at product companies. The new arrow syntax is what interviewers want to see you write.

🔀 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.

javac IfElse.java && java IfElse
IfElse.javaLesson 03 · credit tier routing
verified output
Tier: SILVER — rate 10.0% Pre-approval: YES

⚡ 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.

javac SwitchExpr.java && java SwitchExpr
SwitchExpr.javaLesson 03 · payment-method fee lookup
verified output
Payment method : UPI Transaction fee: ₹0.00 SATURDAY is a HOLIDAY day

📱 Real-world scenario

📱
Real-world scenario · BoraPay
Wanjiku routes transactions by amount tier using switch + yield

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.

javac SwitchYield.java && java SwitchYield
SwitchYield.javaBoraPay · switch with yield blocks
verified output
Amount : ₹75000 Status : High value — 24h review

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

SituationUseWhy
Range checks (>=750, <700)if/elseSwitch can't match ranges
Exact value matching (String, int, enum)switch expressionCleaner, exhaustive, no fall-through
Complex conditions with && / ||if/elseSwitch only tests equality
Single value → multiple outcomesswitch expressionReturns a value directly
3+ branches on same variableswitch expressionMore readable than if/else chain

🧩 Mini challenge

Three branching exercises
Task 1 — Income tax slab

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.

Task 2 — Currency symbol lookup

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.

Task 3 — Rewrite with switch

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

EasyWhat is fall-through in a switch statement and why is it dangerous?
+

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.

EasyCan a switch expression in Java 14+ return a value?
+

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.

MediumWhat types can you switch on in Java 21?
+

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.

MediumWhen should you use if/else instead of switch?
+

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.

HardWhat does exhaustiveness mean for switch expressions and why does it matter?
+

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

Question 1 of 5
In a Java 14+ switch expression, what does yield do?
Question 2 of 5
Which of these is NOT a valid switch selector type in Java?
Question 3 of 5
What problem does the arrow syntax (->) in switch expressions solve?
Question 4 of 5
Given int score = 685, which branch executes in the IfElse example above?
Question 5 of 5
Can a single switch case arm match multiple values in Java 14+?
0
/ 5
Quiz complete!

Next: loops — for, while, do-while →

⚠️ Common mistakes

Forgetting break in old switch
Without 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.
Wrong condition order in if/else
If you write 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.
Missing default in switch
For 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.
Using switch on ranges
Switch cannot match 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 — no break needed.
  • Multiple values can share one arm: case "SAT", "SUN" -> "HOLIDAY".
  • Use yield to return a value from a multi-statement switch block arm.
  • Switch expressions are exhaustive — the compiler rejects missing cases at compile time.
Africa & India's Best AI Academy
🤖 AI-first 🎓 Placement Assistance

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 →