Step 1 of 5 · Reading · ~3 min
Learn
Control Flow
Conditionals
A program decides with if, else if and else. By the end of this lesson you can write a decision with several cases in the right order, combine tests with &&, || and !, and avoid the ordering bugs that make a correct-looking chain give wrong answers.
if / else if / else
int minutes = 42;
if (minutes > 120) {
System.out.println("long");
} else if (minutes > 30) {
System.out.println("medium");
} else {
System.out.println("short");
}
Java walks the chain top to bottom and runs the first branch whose condition is true, then skips the rest. With minutes = 42 only medium prints. else catches everything left over.
The condition must be a boolean
Not a number, not a string, not "anything truthy": a real boolean. That deletes a famous C bug, typing = (assignment) where you meant == (comparison):
if (minutes == 30) { ... } // comparison
if (minutes = 30) { ... } // compile error: int cannot be converted to boolean
Compare text with .equals, never ==: if (answer.equals("yes")).
Combining conditions
if (age >= 18 && hasTicket) { ... } // AND: both true
if (day == 6 || day == 7) { ... } // OR: at least one true
if (!paid) { ... } // NOT: flips it
&& and || short-circuit: if the left side already decides the answer, the right side never runs. That is why s != null && s.length() > 0 is safe: when s is null, the length call is skipped.
Precedence: && binds tighter than ||
Like * before +, && is evaluated before ||. So these differ:
a || b && c // a, or (b and c)
(a || b) && c // (a or b), and c
When a rule has an "except" in it, write the parentheses explicitly. A discount that applies to members, or to anyone on a weekday other than a holiday:
boolean discount = isMember || (isWeekday && !isHoliday);
Drop the parentheses and read the rule back aloud; if you have to think about it, the next reader will too.
Order is logic
In an else if chain the order of the tests is part of the logic. Put the narrowest condition first, because anything that matches an earlier test never reaches a later one:
// CORRECT: narrowest first
if (grams > 20000) {
System.out.println("freight");
} else if (grams > 5000) {
System.out.println("parcel");
} else {
System.out.println("letter");
}
// BROKEN: a 30 kg package matches "> 5000" first
if (grams > 5000) {
System.out.println("parcel");
} else if (grams > 20000) {
System.out.println("freight"); // can never run
}
Every weight over 20000 is also over 5000, so the looser test steals the match. When a rule has exceptions to exceptions, the same idea applies: test the most specific case first, or fold the cases into one boolean expression.
Ternary
For picking one of two values: String size = minutes > 30 ? "long" : "short";. Fine for simple choices, unreadable when nested.
Common mistakes
- Wrong order in an
else ifchain, so a specific case is shadowed by a general one. - Missing parentheses around an
||inside an&&rule, so the rule means something else. ==on strings. Use.equals.- A stray
;after the condition,if (x > 3);, which makes theifdo nothing and the following block always run.
Your exercise
A calendar rule with exceptions: some years get an extra day, but not every year that looks like it should. Decide the order and structure of your tests, and check the year values at the boundaries of each exception, because those are the values that expose a wrong order or a missing parenthesis.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…