The Plain Picture#
A road with a fork and a signpost: "If you're going to Mysore, turn left; otherwise, continue straight." A program checks a question
whose answer is yes/no — a boolean — and takes one path.
The Real Names#
if / else if / else#
if (points >= 200) {
grade = "A";
} else if (points >= PASS_MARK) {
grade = "B";
} else {
grade = "Needs practice";
}Conditions are checked top to bottom; the first true one runs and the rest are skipped. So order matters: checking
points >= 150 before points >= 200 would give 250 a "B".
Always use braces, even for one line. Without them, only the next single statement belongs to the if:
if (onTime) points += 20;
bonusCount++; // ← runs ALWAYS, despite the indentation. A famous class of bugs.The ternary operator — a one-line if/else that produces a value#
String status = points >= 150 ? "pass" : "fail";
// condition ? value if true : value if falseUse it for simple choices; switch to if as soon as it gets nested.
switch — choosing among many fixed values#
The modern form (Java 14+) uses arrows and can produce a value:
int day = 3;
String type = switch (day) {
case 1, 7 -> "weekend";
case 2, 3, 4, 5, 6 -> "weekday";
default -> "invalid";
};
System.out.println(type); // weekdayThe old form still appears in older code and interviews. Its trap is fall-through: without break, execution continues into the
next case.
switch (day) {
case 1:
System.out.println("Sunday");
break; // ← forget this and "Monday" prints too
case 2:
System.out.println("Monday");
break;
default:
System.out.println("Other");
}switch works on int, char, String, enums (Object-Oriented Programming) and — with pattern matching — types (Modern Java).
Check yourself
4 questionsWhy does the order of else if conditions matter?
Show answerHide answer
The first true condition wins and the rest are skipped, so a broader condition placed first can hide a narrower one.
What goes wrong with an if without braces?
Show answerHide answer
Only the next single statement is controlled by the if; later lines run unconditionally, even if indented.
Rewrite as a ternary: if score > 100, level = "pro", otherwise level = "beginner".
Show answerHide answer
String level = score > 100 ? "pro" : "beginner";
What is fall-through in an old-style switch?
Show answerHide answer
Without break, execution continues into the following case's code.