Part of: Java for Beginners › Control Flow and Loops
1. Exclusive Branching: if, else if, else
if / else if branches evaluate sequentially downwards. As soon as one condition evaluates to true, its block executes and all remaining branches are skipped.
When neither condition matches, the thread of execution falls naturally into the catch-all else clause.
2. The Ternary Operator: Inline Conditional
The ternary operator (? :) is a compact expression yielding one of two values based on a boolean condition. Unlike if statements, it evaluates to an assignable value.
Golden rule: Use ternaries only for simple, punchy decisions. Nesting ternaries ruins code readability.
3. Classic switch (Fall-through) vs Modern switch (->)
In classic switch statements, omitting break causes dangerous fall-through. Java 14 introduced arrow syntax (->) eliminating fall-through bugs by design.
Without a break, execution falls through to case 2 and overwrites "Monday". With arrow syntax, each branch is strictly isolated.
4. The 4-Step Clock of the for Loop
A for loop does not run all its clauses at once. It follows a rhythmic 4-step sequence: 1. Init (once), 2. Condition check, 3. Body, 4. Increment. Then loops back to step 2.
Click "Tick Step" to observe the clock hand visit each phase of the loop cycle.
5. while vs do-while: Where is the Turnstile?
In a while loop, the condition checks at the gate: if false, the body runs 0 times. In a do-while loop, execution runs first and validates at exit: guaranteed to run at least 1 time.
Because the condition is false upfront, the while body is completely bypassed.
6. Loop Control: break vs continue
break immediately terminates the entire loop and jumps past it. continue skips only the remainder of the current iteration and advances straight to the next.
Control Flow Summary
- if / else if: Sequential short-circuiting; executes strictly one branch.
- switch con flechas (->): Eliminates fall-through bugs without needing break.
- for de 4 tiempos: Init (1) -> Condition (2) -> Body (3) -> Increment (4).
- do-while: Validated at exit gate; guarantees at least one execution.