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
ifchain runs. - Compare strings with
equalsinside conditions too. - Classic
switchneedsbreak; the arrow-form switch expression does not, and returns a value. - Compare doubles with a tolerance.
Next: loops.