beginnerFree

Control Flow

if/else - make decisions in code

Control Flow

Control flow lets your program choose different paths based on conditions.

The narrated version of this skribble — tap play for the full-size video.

0:00 / 2:17

The Big Picture

Control flow directs which code runs based on conditions. Without it, code runs top to bottom every time.

  • if/else: basic branching
  • switch: multi-way branching on a value
  • Ternary: condition ? valueA : valueB

Every program beyond hello-world uses control flow.

How It Works

The JVM evaluates boolean expressions and jumps to branches.

  • if evaluates once; else if chains checked in order
  • Short-circuit: && stops if left is false
  • switch can compile to a jump table; mainly clearer than long if/else
  • Java 14+ switch expressions return values directly
  • Pattern matching (Java 21+) adds type checks to switch

In the Java Landscape

Control flow is fundamental - used in every Java construct.

  • Modern switch (Java 14+): case "A" -> doA();
  • Java 21 pattern switch + sealed types enables exhaustive type switches
  • Optional reduces null-checking if/else chains
  • Streams replace some conditional loops with filter()
  • Strategy pattern replaces complex if/else with polymorphism

Pitfalls and Best Practices

  • Always use braces even for single-line if blocks
  • Don't nest more than 3 levels deep - extract methods
  • Use early returns to flatten nested conditions
  • switch fall-through is a common bug - use break
  • Prefer switch expressions (Java 14+) - no fall-through
  • Replace boolean flags with meaningful method names
#java#fundamentals#control-flow