Java · Module 3 · Lesson 11 min read

If, Else & Switch

if / else if / else

Java
int marks = 72;
if (marks >= 90) {
    System.out.println("A");
} else if (marks >= 60) {
    System.out.println("B");
} else {
    System.out.println("Try again!");
}
  • Conditions must be boolean. if (x = 5) won't compile in Java; use ==.
  • Only the first true branch runs.
  • Always use { }, even for one line. It prevents sneaky bugs.

Nested conditions

You can put an if inside another if, but too much nesting gets hard to read. Combine conditions with && and || when you can.

Classic switch

Java
switch (day) {
    case 1:
        System.out.println("Monday");
        break;
    case 6:
    case 7:
        System.out.println("Weekend!");
        break;
    default:
        System.out.println("Weekday");
}

⚠️ Without break, execution falls through into the next case.

Switch expressions (Java 14+) ✨

Shorter, safer, and no fall-through:

Java
String type = switch (day) {
    case 6, 7 -> "Weekend";
    case 1, 2, 3, 4, 5 -> "Weekday";
    default -> "Invalid";
};

Use yield to return a value from a block: case 1 -> { log(); yield "Mon"; }

switch works with int, char, String, enums and (in newer Java) patterns.

Example

Java
public class GradeBot {
    public static void main(String[] args) {
        int score = 85;
        String grade = score >= 90 ? "A" : score >= 75 ? "B" : "C";

        String message = switch (grade) {
            case "A" -> "Legendary! 🏆";
            case "B" -> "Great job! 🎉";
            default  -> "Keep practising 💪";
        };
        System.out.println(grade + " — " + message);  // B — Great job! 🎉
    }
}