jario_
Back to overview

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 >=.

You can change the code and run it again.

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").

You can change the code and run it again.

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.

You can change the code and run it again.

Common mistakes

  • = instead of ==

    = assigns a value, == compares. The compiler rejects if (age = 18) with incompatible 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 often false even though they look the same. Always use equals:

    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. If if (points >= 50) comes before else if (points >= 90), the second branch is never reached. Check the narrower condition first.

  • Missing default in a switch expression

    If a switch produces a value, every possible value must be covered. Without default, the compiler reports the switch expression does not cover all possible input values.