</>CodexBash
Java
JavaBeginner9 min

Decisions with if and switch

Choosing what runs with if, else if and else, the ternary operator, the classic switch with break, and the modern switch expression that returns a value.

An if / else if chainstep 1/5
>=90
A
>=75
B
>=60
C
else
F
marks = 72
marks is 72. Each condition is checked in order, top to bottom.

if, else if, else#

int marks = 72;
String grade;

if (marks >= 90) {
    grade = "A";
} else if (marks >= 75) {
    grade = "B";
} else if (marks >= 60) {
    grade = "C";
} else {
    grade = "F";
}

Only the first true branch runs, so the order of checks matters. Java also checks that grade is definitely given a value on every path before you use it; remove the final else and the compiler will point that out.

Always use braces, even for one line, so a second line cannot quietly escape the if.

Combining conditions#

if (age >= 18 && hasTicket) { ... }
if (day.equals("Saturday") || day.equals("Sunday")) { ... }
if (!found) { ... }

Note equals for strings.

The ternary operator#

int larger = (a > b) ? a : b;
String parity = (n % 2 == 0) ? "even" : "odd";

The classic switch#

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, which is almost always a bug. Java's switch works on integers, characters, enums and strings.

The switch expression#

Modern Java (14 and later) has a cleaner form that returns a value, uses arrows instead of break, and never falls through:

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

int points = switch (grade) {
    case "A" -> 4;
    case "B" -> 3;
    case "C" -> 2;
    default -> 0;
};

Prefer this form in new code: it is shorter, and a missing case is far easier to spot.

Comparing doubles#

Floating-point results are approximate, so compare with a tolerance:

double x = 0.1 + 0.2;
if (Math.abs(x - 0.3) < 1e-9) { ... }    // true

Handling special cases first#

static int digits(int n) {
    if (n == 0) return 1;
    int count = 0;
    while (n != 0) {
        n /= 10;
        count++;
    }
    return count;
}

Key points#

  • Only the first true branch of an if chain runs.
  • Compare strings with equals inside conditions too.
  • Classic switch needs break; the arrow-form switch expression does not, and returns a value.
  • Compare doubles with a tolerance.

Next: loops.

Practise it

The same idea, in the order it is worth meeting it.

  1. Not startedReads the same backwardsEasy
Create a free account to track your progress