Conditional Statements

Conditional statements let your program make decisions and run different code depending on whether a condition is true or false. Java gives you if, if-else, if-else if-else chains, the ternary operator, and switch.

The if Statement

Runs a block of code only when its condition evaluates to true.

int age = 20;

if (age >= 18) {
  System.out.println("You are an adult.");
}

The if-else Statement

Adds an alternative block that runs when the condition is false.

int age = 15;

if (age >= 18) {
  System.out.println("You are an adult.");
} else {
  System.out.println("You are a minor.");
}

The if-else if-else Chain

Checks multiple conditions in order and runs the first block whose condition is true.

int score = 72;

if (score >= 90) {
  System.out.println("Grade: A");
} else if (score >= 75) {
  System.out.println("Grade: B");
} else if (score >= 60) {
  System.out.println("Grade: C");
} else {
  System.out.println("Grade: F");
}

The Ternary Operator

A compact one-line alternative to a simple if-else: condition ? valueIfTrue : valueIfFalse. It's an expression, so it produces a value you can assign directly.

int age = 20;
String status = (age >= 18) ? "Adult" : "Minor";

System.out.println(status); // Adult

The switch Statement

switch compares one value against several possible cases. The traditional syntax uses a colon after each case label and needs a break to stop execution from "falling through" into the next case.

int day = 3;
String dayName;

switch (day) {
  case 1:
    dayName = "Monday";
    break;
  case 2:
    dayName = "Tuesday";
    break;
  case 3:
    dayName = "Wednesday";
    break;
  default:
    dayName = "Unknown";
}

System.out.println(dayName); // Wednesday
Note: Forgetting break is a classic bug — execution "falls through" and keeps running the next case's code too.

Java 14 introduced a newer arrow syntax for switch that removes the need for break and avoids fall-through entirely. Each case maps directly to a result with ->.

int day = 3;

String dayName = switch (day) {
  case 1 -> "Monday";
  case 2 -> "Tuesday";
  case 3 -> "Wednesday";
  default -> "Unknown";
};

System.out.println(dayName); // Wednesday
Tip: Use the ternary operator for tiny decisions, if-else chains for a handful of branching conditions, and switch when comparing one variable against many fixed values. Next up: Loops.