Branches

if reads a boolean, not "something that looks like true".

if accepts only a boolean. A number, a string or an object will not do: if (n) for an int does not compile. This is stricter than JavaScript and PHP, and that is exactly why you have to write the condition explicitly: n != 0, text.isEmpty(), user != null.

The order of branches matters. The first true branch wins, and the rest are not looked at. The condition n > 0 placed before n > 10 never lets large numbers reach the second branch. Put narrow conditions before wide ones, or better, avoid overlapping branches altogether.

The ternary operator cond ? a : b is an expression: it has a value. Both branches must lead to one type or a common ancestor. For two strings that is handy. For a business rule with five branches, a ternary ladder is unreadable: use an ordinary if.

Do not stack negations. if (!user.isActive()) reads fine. if (!(!(n > 0))) does not. Move the condition into a method with a name: isAdult(user). A method name is documentation that the compiler also checks.

Practice

  1. What if accepts

    What type must the condition in an if have?

    • int
    • String
    • boolean
    • any object
  2. Which branch runs

    n equals 12. The branches go like this: if (n > 0) return plus; else if (n > 10) return big. What is returned?

  3. The sign of a number

    Write static String sign(int n). Return plus for a positive number, minus for a negative one and zero for zero.