Branching and Loops

Java provides if/else, switch, for, enhanced for, while, and do-while. Modern Java also supports switch expressions, which can return a value.

int score = 82;

String result = switch (score / 10) {
    case 10, 9 -> "Excellent";
    case 8 -> "Good";
    case 7 -> "Average";
    default -> "Needs improvement";
};

for (int i = 0; i < 5; i++) {
    System.out.println(i);
}

Prefer the construct that expresses intent most clearly. Enhanced for is ideal for straightforward iteration. Streams are useful when the operation is naturally a data transformation pipeline; they are not automatically better than a loop.

Key Takeaways
  • Use switch expressions when a branch naturally produces a value.
  • Enhanced for improves readability for collection traversal.
  • Choose loops and streams based on clarity and semantics.