Java - Control Flow (if/else, switch)

Control Flow

if / else if / else

Use guard clauses to exit early and keep nesting shallow.

int score = 85;
if (score < 0 || score > 100) {
  throw new IllegalArgumentException("score out of range"); // guard clause
}
if (score >= 90) {
  System.out.println("A");
} else if (score >= 80) {
  System.out.println("B");
} else {
  System.out.println("C or below");
}

switch on Strings and Enums

enum Color { RED, BLUE }
Color c = Color.BLUE;
switch (c) {
  case RED -> System.out.println(1);
  case BLUE -> System.out.println(2);
}

String s = "blue";
switch (s) {
  case "red" -> System.out.println(1);
  case "blue" -> System.out.println(2);
  default -> System.out.println(0);
}

Switch Expressions (Java 14+)

int days = switch (java.time.Month.FEBRUARY) {
  case APRIL, JUNE, SEPTEMBER, NOVEMBER -> 30;
  case FEBRUARY -> 28;
  default -> 31;
};
Avoid fall-through unless intentional. The arrow (->) form prevents accidental fall-through.

Try it

  1. Convert a traditional switch to a switch expression returning a value.
  2. Write guard clauses to validate function inputs and throw IllegalArgumentException on invalid data.