Programs rarely do the exact same thing every time; they need to react differently depending on the situation. Java offers if, else and switch as the core tools for making these decisions, and knowing when each fits best makes conditional code far easier to read.

The if statement

if (age >= 18) {
  System.out.println("Adult");
}

The code inside the braces only runs when the condition evaluates to true. If the condition is false, that block is simply skipped.

Adding else and else if

if (score >= 90) {
  grade = "A";
} else if (score >= 80) {
  grade = "B";
} else {
  grade = "C";
}

Java checks each condition from top to bottom and stops at the first one that matches, which is why order matters here: a score of 95 matches the first condition and never even reaches the later checks.

A common mistake

Using a single equals sign instead of two inside a condition is one of the most frequent beginner errors. Writing if (isReady = true) assigns the value true to isReady rather than comparing it, and in Java this specific mistake usually fails to compile when isReady is a boolean, which is one small safety net the language provides compared to some others.

The switch statement

When one value is compared against several fixed options, switch is often cleaner than a long chain of else if statements:

switch (day) {
  case 1: name = "Mon"; break;
  case 2: name = "Tue"; break;
  default: name = "Other";
}

The break keyword stops execution from falling through into the next case; forgetting it is a classic bug where more code runs than intended. The default case runs when nothing else matches, similar to a final else.

Modern switch expressions

Newer versions of Java allow switch to be used as an expression that directly produces a value, using an arrow instead of a colon, which also removes the need for break entirely:

String name = switch (day) {
  case 1 -> "Mon";
  case 2 -> "Tue";
  default -> "Other";
};

The ternary operator

For a simple choice between two values, the ternary operator condenses an entire if-else into one line:

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

Choosing the right tool

Use if and else for a small number of distinct conditions, especially ones involving comparisons like greater than or less than. Reach for switch once several fixed, specific values are being compared against a single variable, and save the ternary operator for short, simple choices where a full if-else would only add unnecessary length.