Chapter 2
Conditions
So far, every program ran stubbornly from top to bottom. With conditions it makes decisions: depending on the input, one part or another is run.
if, else if, else
After if comes a condition in parentheses. If it's true, the block in curly braces runs. Otherwise Java moves on to else if (the next condition) or else (all remaining cases). Java checks from top to bottom and takes only the first matching branch.
To compare, there's == (equal), != (not equal), <, <=, > and >=.
Try the inputs -5, 0 and 15. With 15, temperature < 15 is false, so the program ends up in else.
Truth values and combining them
A condition is a value of type boolean: true or false. You can store it in a variable and combine it:
a && b: both must be true (and)a || b: at least one must be true (or)!a: flips the value (not)
&& binds more tightly than ||. When in doubt, add parentheses, which also makes it clear to read.
Compare texts with equals, not with ==: command.equals("stop").
switch
If you check one variable against several fixed values, switch is clearer than a long else if chain. Each case goes after case, and after the arrow -> comes what should happen. Separate several values with commas. default covers all remaining values. switch works with whole numbers and with texts.
A switch can also produce a value (a switch expression). Then it stands to the right of = or after return, ends with a semicolon and needs a case for every possible value, usually via default.
Common mistakes
= instead of ==
=assigns a value,==compares. The compiler rejectsif (age = 18)withincompatible types: int cannot be converted to boolean.Comparing texts with ==
For texts,
==checks whether it's the same object, not whether the letters are the same. With texts you read in, that's oftenfalseeven though they look the same. Always useequals:if (answer.equals("yes")) { ... }Semicolon after if
if (x > 10);is a condition with an empty statement. The block after it then always runs. The curly brace belongs directly after the closing parenthesis.Wrong order
With
else if, the first matching branch wins. Ifif (points >= 50)comes beforeelse if (points >= 90), the second branch is never reached. Check the narrower condition first.Missing default in a switch expression
If a
switchproduces a value, every possible value must be covered. Withoutdefault, the compiler reportsthe switch expression does not cover all possible input values.