JvJava
BeginnerLesson 3 of 16

Conditions, if & switch – Java

Making decisions – including the modern switch expression.

if, else if and else work as in many languages. The condition must be a boolean (no 0/1 as in C). You combine conditions with &&, || and !.

int punkte = 73;
String note;
if (punkte >= 90) {
    note = "very good";
} else if (punkte >= 70) {
    note = "good";
} else {
    note = "needs improvement";
}
System.out.println(note);            // good

int alter = 20;
String status = alter >= 18 ? "adult" : "minor";  // ternary
System.out.println(status);

The modern switch expression (Java 14+) returns a value, uses -> instead of : and has no fall-through (no break needed). You separate several values with a comma.

int tag = 6;
String art = switch (tag) {
    case 6, 7 -> "Weekend";
    case 1, 2, 3, 4, 5 -> "Weekday";
    default -> throw new IllegalArgumentException("Invalid day: " + tag);
};
System.out.println(art);             // Weekend

If a branch needs several statements, you use a block and return the value with yield:

int punkte = 85;
String note = switch (punkte / 10) {
    case 10, 9 -> "very good";
    case 8, 7 -> {
        System.out.println("Intermediate result calculated");
        yield "good";
    }
    default -> "needs improvement";
};
System.out.println(note);            // Intermediate result calculated / good
WarningThe old style case 1: ... break; has "fall-through": without break the next case simply runs as well. So prefer the arrow syntax.