🧠 Java Quiz

If / Else & Switch

Make your program take different paths based on conditions.

if / else if / else

Basic if/else
int score = 85;

if (score >= 90) {
    System.out.println("A");
} else if (score >= 80) {
    System.out.println("B");
} else if (score >= 70) {
    System.out.println("C");
} else {
    System.out.println("F");
}

Java evaluates conditions top-down and stops at the first match. Braces aren't required for single-statement bodies, but always use them — it prevents bugs.

The classic single-line bug
if (loggedIn)
    log("Welcome");
    redirectToHome();   // Always runs! Indentation lies.

Nested if

Nested
if (loggedIn) {
    if (isAdmin) {
        showAdminPanel();
    } else {
        showUserPanel();
    }
}

switch statement (classic)

When you have many discrete values to check against:

switch
int day = 3;
String name;
switch (day) {
    case 1: name = "Monday"; break;
    case 2: name = "Tuesday"; break;
    case 3: name = "Wednesday"; break;
    case 4: name = "Thursday"; break;
    case 5: name = "Friday"; break;
    default: name = "Weekend";
}
System.out.println(name);  // "Wednesday"
Don't forget break! Without break, execution "falls through" to the next case — a common bug source. Each case should usually end with break or return.

switch expression (Java 14+) — modern

The new arrow syntax — concise, returns a value, no fall-through:

switch expression
int day = 3;
String name = switch (day) {
    case 1 -> "Monday";
    case 2 -> "Tuesday";
    case 3 -> "Wednesday";
    case 4 -> "Thursday";
    case 5 -> "Friday";
    case 6, 7 -> "Weekend";
    default -> "Unknown";
};

Note: multiple values per case (case 6, 7), no break needed, returns directly.

switch with strings

String cases
String command = "start";
switch (command) {
    case "start" -> startServer();
    case "stop"  -> stopServer();
    case "restart" -> { stopServer(); startServer(); }
    default -> System.out.println("Unknown command");
}