Conditionals
If/Else — The Fork in the Road
Imagine you're walking and the path splits. You check: "Is it raining?" If yes, you take the covered path. If no, you take the scenic route. That's exactly what if/else does in Java.
The condition inside the parentheses must be a boolean expression — something that evaluates to true or false. Branching like this is at the heart of binary search and many other algorithms. Java checks it, picks one path, and ignores the other.
You can also chain decisions with else if when you have more than two options — like choosing between walking, biking, or taking the bus based on the distance.
If / Else If / Else
Switch — The Vending Machine
A switch statement is like a vending machine. You put in a value, and it checks which button matches. It's cleaner than writing a dozen else if blocks when you're comparing one variable against many exact values.
Important rules:
- Each
caseneeds abreak;at the end, or Java will "fall through" and run the next case too. - The
defaultcase runs when nothing else matches — like the "invalid selection" message on a vending machine. - Switch works with
int,char,String, and enums (but notdoubleorboolean).
Switch Statement
Comparing Strings in Conditions
break in your switch? Java will "fall through" and execute every case below the matching one. This is occasionally useful on purpose (like grouping Saturday and Sunday), but usually it's a bug. When in doubt, always add break.