An if statement is the point where a program stops being a straight line. It takes a boolean condition, and runs the block that follows only when that condition is true. Add else and you have a fork with exactly two outcomes; add else if and you have a chain of outcomes tested in order. Everything a program decides, from a grade label to a game rule, is built from these three words.
int mark = 74;
if (mark >= 50) {
System.out.println("Pass");
} else {
System.out.println("Below 50");
}
System.out.println("Done"); // runs either way — it is outside both blockselse if chains, and why order matters
int mark = 85;
// BROKEN: the first true condition wins, and >= 50 is true for 85.
if (mark >= 50) {
System.out.println("Level 1");
} else if (mark >= 60) {
System.out.println("Level 2");
} else if (mark >= 70) {
System.out.println("Level 3");
} else if (mark >= 80) {
System.out.println("Level 4");
}
// prints: Level 1An else if chain is tested from the top down, and the moment a condition is true its block runs and every remaining condition is skipped entirely. So a chain of overlapping ranges must be ordered from the most demanding condition to the least. With the broken order above, a mark of 85 satisfies mark >= 50 first and is labelled Level 1; the mark >= 80 test is unreachable for every mark that would have passed it. The compiler cannot help, because nothing about it is illegal — it is a pure logic error.
int mark = 85;
if (mark >= 80) {
System.out.println("Level 4");
} else if (mark >= 70) {
System.out.println("Level 3");
} else if (mark >= 60) {
System.out.println("Level 2");
} else if (mark >= 50) {
System.out.println("Level 1");
} else {
System.out.println("Below Level 1");
}
// prints: Level 4Nesting versus combining
int age = 16;
boolean hasPermit = true;
// Nested: useful when each level needs its own else message.
if (age >= 16) {
if (hasPermit) {
System.out.println("May drive with a supervisor");
} else {
System.out.println("Old enough, but no permit yet");
}
} else {
System.out.println("Too young");
}
// Combined: shorter, but only one failure message is possible.
if (age >= 16 && hasPermit) {
System.out.println("May drive with a supervisor");
}The ternary operator
int n = 7;
String parity = (n % 2 == 0) ? "even" : "odd"; // "odd"
int a = 4, b = 11;
int larger = (a > b) ? a : b; // 11
System.out.println(n + " is " + parity); // 7 is odd
System.out.println("Larger: " + larger); // Larger: 11The ternary operator is the only Java operator that takes three operands: a condition, a value to use when it is true, and a value to use when it is false. It is an expression rather than a statement, so it can sit directly inside an assignment or a println. Reach for it when both branches simply choose between two values; if either branch needs to do more than one thing, a plain if is clearer and you should use that instead.