iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

if / else

Java’s if, else if, and else are statements that branch on a boolean expression. Java 14’s switch expression (arrow syntax) is the modern way to chain many branches that return a value.

if / else, ternary, switch expressions, patterns

EXAMPLE
public class Demo {
    public static void main(String[] args) {
        var age = 36;

        // 1) Classic if / else
        if (age >= 18) System.out.println("adult");
        else if (age >= 13) System.out.println("teen");
        else System.out.println("kid");

        // 2) Ternary
        String tier = age >= 65 ? "senior" : age >= 18 ? "adult" : "minor";

        // 3) Switch statement — old style (with break + fall-through)
        switch (age) {
            case 0: case 1: case 2:
                System.out.println("toddler"); break;
            default:
                System.out.println("other");
        }

        // 4) Switch EXPRESSION (Java 14+) — modern, returns a value
        var label = switch (tier) {
            case "senior" -> "Senior pricing";
            case "adult"  -> "Standard pricing";
            case "minor"  -> "Free entry";
            default       -> "Unknown";
        };
        System.out.println(label);

        // 5) Switch with patterns (Java 21+)
        Object o = 42;
        var description = switch (o) {
            case Integer i when i > 0  -> "positive int " + i;
            case Integer i              -> "non-positive int";
            case String s               -> "string of length " + s.length();
            case null                    -> "null";
            default                      -> "something else";
        };
        System.out.println(description);
    }
}

Why it matters

Switch expressions are exhaustive: the compiler will tell you when you forget a case (on enums / sealed types). They’re the modern default — faster, safer, prettier than the old statement form.

Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.

Example

Example
int n = 7;
if (n > 10) {
    System.out.println("big");
} else if (n > 0) {
    System.out.println("small");
} else {
    System.out.println("non-positive");
}
Try it Yourself »

Discussion

Loading…