Decisions: if, else and switch
Comparing values, joining conditions with and, or and not, choosing a path with if and else, and picking one case with switch.
Conditions are questions with a yes or no answer
A condition is anything that comes out true or false. temperature > 30 is one, and so is paid == false. The comparison signs are the ones you know: greater than, less than, and the double equals sign for asking whether two values are the same.
Join conditions with && for and, || for or, and a leading ! for not. temperature > 30 && weekend is true only when both halves are true. Java is lazy about this: if the left half settles the answer, the right half is never evaluated.
if, else if and else
An if runs a block when its condition is true. An else runs instead when it is false, and else if lets you ask a second question when the first answer was no. The chain is read from the top, and the first block that matches is the only one that runs.
The braces are optional for a single statement, but writing them every time is the habit that saves you later. The habit earns its keep when a branch grows: a second statement added under a brace-less if runs whatever the condition said, and nothing in the compiler objects. A short either-or choice can also be written as an expression: weekend ? "ice cream" : "work" gives one value when true and another when false.
switch, for a list of cases
When one value can be one of several known things, switch says it more plainly than a stack of else-ifs. Each case names a value and runs when the value matches; default catches everything else.
Every case here ends with break, which stops the switch from falling through into the next case. Leaving break out is occasionally deliberate, and far more often the bug in the program.
Conditions are values
Every comparison produces a boolean, and a boolean can be stored, passed and returned. boolean hot = temperature > 30; is legal and often clearer than repeating the comparison. The same value can drive an if, a loop or a ternary.
&& and || short-circuit: the right side runs only when the left side has not already decided. That is why name != null && name.length() > 0 is safe, and why putting the necessary test first matters. If the left side settles the answer, the right side never runs.
Switch, strings and fall-through
A switch can choose on a String as well as a number, and it compares with equals rather than ==. Each case needs a constant value known at compile time; a range such as temperature > 30 belongs in an if chain.
Fall-through is the default in the classic switch: without break, the next case runs too. Grouping empty cases is the deliberate use — several labels sharing one block — and a missing break in the middle is the accident. The newer arrow form, case 1 -> ..., removes the ambiguity but is not needed to read the classic one.
Guard clauses, and leaving early
A long if chain has one habit that keeps it readable: answer the easy cases first and leave. A guard clause is an if at the top of a method that returns early when the input cannot be used, so the rest of the method can assume the good case. if (items.isEmpty()) return; removes one level of indentation from everything below it, and indentation is what makes a chain hard to follow.
The same idea applies inside a loop. Rather than wrapping the body in a condition, test the value that cannot be handled and continue. The reader then meets the exceptional case first and reads the ordinary work without a second question in mind. Both forms are the same logic; the difference is how many things you have to hold at once while reading.
A chain, a combination, a choice and a switch
int temperature = 31;
boolean weekend = true;
if (temperature > 30) {
System.out.println("Hot.");
} else if (temperature > 18) {
System.out.println("Pleasant.");
} else {
System.out.println("Take a coat.");
}
if (temperature > 30 && !weekend) {
System.out.println("Hot, and stuck inside.");
}
String plan = weekend ? "ice cream" : "work";
switch (temperature) {
case 31: System.out.println("Exactly 31"); break;
default: System.out.println("Some other temperature");
}Three decisions in one program
Press Run and read all three lines. Then change the weekend flag to false and predict what moves before you run it again, and add a case of your own to the switch.
Three decision mistakes: writing = where you meant ==, comparing doubles with ==, and leaving out break. The first usually fails to compile; the second fails only when the values are very close; the third runs code from the next case and can look like a mysterious extra line of output.
Try these next
- Turn a numeric score into a letter grade with an if and else-if chain, then rewrite the same ladder as a switch on the tens digit.
- Store a condition in a boolean, print it, and use it in an if; confirm the output is the same as writing the comparison twice.
- Remove a break from a switch with two matching cases, predict the extra output, then put it back.
A delivery charge, chosen three ways
Press Run and match each printed line to the branch that produced it. Then change the item count and the member flag, predict the charge before running, and add a case for a day of your own.
One equals sign assigns, two compare. Writing if (paid = true) is a different statement entirely — the compiler usually stops you, but the habit of writing paid on its own for a boolean is safer.
Check what you learned
One question at a time. A wrong answer explains itself — take another go.
Part 1 of 5
When is a && b true?
