If ... Else: Decision Making

If ... Else: Decision Making in Java: Imagine a self-driving car. IF the light is red, THEN stop. ELSE IF the light is yellow, THEN slow down.

Concept Explanation

Imagine a self-driving car.

  • IF the light is red, THEN stop.
  • ELSE IF the light is yellow, THEN slow down.
  • ELSE (it must be green), THEN go.

Decisions in Java work exactly the same way using boolean logic.


Syntax or Core Structure

int speed = 80;

if (speed > 100) {
    System.out.println("Emergency Braking!");
} else if (speed > 70) {
    System.out.println("Slow down a bit.");
} else {
    System.out.println("Perfect speed.");
}

Ternary Operator (The Shortcut)

For simple "Either/Or" decisions, use this shorthand: variable = (condition) ? expressionTrue : expressionFalse;

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

Common Mistakes

  1. The Double Equals: Using if (x = 10). This assigns 10 to x! Use if (x == 10).
  2. String Comparison: Using if (name == "John"). In Java, you MUST use .equals() for strings: if (name.equals("John")).
  3. Hanging Else: Forgetting curly braces for single-line if-statements. It's safer to always use { }.

Practice Exercises

  1. The Grade Calculator: Write a program that takes a score (0-100) and prints A, B, C, D, or F.
  2. The Leap Year: Research the rules for a Leap Year and write an if statement to check if a year variable is a leap year.
  3. The Password Switch: Compare a guessedPassword String with a correctPassword using .equals() and print "Access Granted" or "Denied".