Part 1 · The core language

3Decisions

Until now every program you wrote ran the same statements in the same order every time. Real programs choose: they do one thing when a number is large and another when it is small, and they refuse input that makes no sense. This lesson is about how a Java program asks a yes-or-no question about its data and acts on the answer, using if, else, the logical operators and switch.

By the end you will be able to

  • write conditions with comparison and logical operators, and work out their value by hand
  • choose between if, else if chains, the conditional operator and switch for a given decision
  • explain why a variable declared inside a block cannot be used after it, and why the order of tests in a chain matters
  • use short-circuit evaluation to guard against a crash, and rewrite a condition with De Morgan's laws
  • recognise the silent mistakes of this topic (a stray semicolon, missing braces, a forgotten break) and read the compiler messages for the loud ones

Nothing in this lesson reads input yet. Each program gets its data from variables set at the top of main. To explore, change a value, save, compile and run again. Every example program on this page is in code/m03-decisions, and the output shown was produced by running it. The exercise programs live in your own work folder, not there.

Conditions: questions with a yes-or-no answer

You met boolean in lesson 2: a type with exactly two values, true and false. A condition is any expression whose value is a boolean. The simplest conditions come from the six comparison operators, which compare two values and produce a boolean.

OperatorMeaningExampleValue when age is 17
==is equal toage == 17true
!=is not equal toage != 17false
<is less thanage < 18true
>is greater thanage > 17false
<=is less than or equal toage <= 17true
>=is greater than or equal toage >= 18false

A comparison is an expression like age + 1: it has a value, and you can print it or store it. The difference is the type of that value.

code/m03-decisions/Compare.java
public class Compare {
    public static void main(String[] args) {
        int age = 17;
        System.out.println(age >= 18);
        System.out.println(age == 17);
        System.out.println(age != 17);
        System.out.println(age < 18);

        boolean isAdult = age >= 18;
        System.out.println("isAdult is " + isAdult);

        boolean isMinor = age < 18;
        System.out.println(isAdult == isMinor);
        System.out.println(isAdult != isMinor);
    }
}
Terminal, in code/m03-decisions
> javac Compare.java
> java Compare
false
true
false
true
isAdult is false
false
true

The first four lines print comparisons directly. Line 9 stores one in a boolean variable, and from then on isAdult can be used wherever a condition is wanted. The last two lines show that == and != also work between two boolean values. The other four operators need numbers (or chars, which lesson 2 showed are numbers underneath).

Name boolean variables so that they read as a question: isAdult, hasTicket, windowOpen. Then if (isAdult) reads like English, and there is never a reason to write if (isAdult == true): the variable already is a true or a false.

The classic slip: = is not ==

One equals sign assigns. Two compare. Mixing them up is the most common mistake in this topic, so see what Java does with it. In many languages if (x = 5) runs without complaint. In Java, with an int, it does not:

code/m03-decisions/broken/AssignInIf.java
public class AssignInIf {
    public static void main(String[] args) {
        int x = 3;
        if (x = 5) {
            System.out.println("x is five");
        }
    }
}
Terminal, in code/m03-decisions/broken
> javac AssignInIf.java
AssignInIf.java:4: error: incompatible types: int cannot be converted to boolean
        if (x = 5) {
              ^
1 error

An assignment is itself an expression, and its value is the value that was assigned. So x = 5 has the value 5, an int, and an if wants a boolean. The compiler's message says exactly that: it found an int where a boolean was required. Java also does not treat any number as true or false, so if (5) is refused for the same reason.

The slip is not always caught. When the variable is itself a boolean, the assignment has a boolean value and the compiler is satisfied:

code/m03-decisions/AssignBool.java
public class AssignBool {
    public static void main(String[] args) {
        boolean ready = false;
        if (ready = true) {
            System.out.println("Starting.");
        }
        System.out.println("ready is now " + ready);
    }
}
Terminal, in code/m03-decisions
> javac AssignBool.java
> java AssignBool
Starting.
ready is now true

The compiler said nothing. ready was false, the condition set it to true, and that value (true) made the block run. The program ran the block and destroyed the data it meant to test. If you want to test a flag, write if (ready), which has no = to get wrong.

Making a choice: if, else and chains

if

An if statement runs a block of statements only when its condition is true.

if (condition) {
    statements that run when the condition is true
}

The condition goes in parentheses, which are required. The statements go in a block: everything between a pair of braces. If the condition is false, Java skips the whole block and carries on after the closing brace.

code/m03-decisions/IfOnly.java
public class IfOnly {
    public static void main(String[] args) {
        int temperature = 4;
        System.out.println("Temperature: " + temperature);
        if (temperature < 5) {
            System.out.println("Take a coat.");
        }
        if (temperature > 25) {
            System.out.println("Wear sun cream.");
        }
        System.out.println("Have a good day.");
    }
}
Terminal, in code/m03-decisions
> javac IfOnly.java
> java IfOnly
Temperature: 4
Take a coat.
Have a good day.

The first condition, 4 < 5, is true, so its block ran. The second, 4 > 25, is false, so Wear sun cream. was skipped. The last statement is outside both blocks and runs regardless.

else

Adding else gives the program a second block that runs when the condition is false. Exactly one of the two blocks runs, never both and never neither.

statements before condition? true the if block runs false the else block runs statements after

Read the diagram from the left. The diamond is the one point where the program chooses. Whichever way it goes, the two paths meet again, and execution continues with whatever follows the whole if/else. Without an else, the lower path simply has nothing on it.

code/m03-decisions/IfElse.java
public class IfElse {
    public static void main(String[] args) {
        int balance = 40;
        int price = 55;
        if (balance >= price) {
            balance -= price;
            System.out.println("Purchase complete.");
        } else {
            System.out.println("Not enough money. You need " + (price - balance) + " more.");
        }
        System.out.println("Balance: " + balance);
    }
}
Terminal, in code/m03-decisions
> javac IfElse.java
> java IfElse
Not enough money. You need 15 more.
Balance: 40

The balance of 40 is less than the price of 55, so the condition on line 5 was false and the else block ran. Notice that balance -= price; in the first block did not run, and the balance is still 40.

else if: more than two outcomes

When there are three or more outcomes, put another if after an else. The result is a chain. Java works down it from the top, tests each condition in turn, runs the block of the first one that is true, and skips every test and block below it. A final plain else, if there is one, runs when none of the conditions was true.

code/m03-decisions/GradeChain.java
public class GradeChain {
    public static void main(String[] args) {
        int score = 85;
        String grade;
        if (score >= 70) {
            grade = "Distinction";
        } else if (score >= 50) {
            grade = "Merit";
        } else if (score >= 40) {
            grade = "Pass";
        } else {
            grade = "Fail";
        }
        System.out.println("Score " + score + ": " + grade);
    }
}
Terminal, in code/m03-decisions
> javac GradeChain.java
> java GradeChain
Score 85: Distinction

With a score of 85, the first test (score >= 70) is true, so grade becomes "Distinction" and the two remaining tests are never looked at. Line 4 declares grade before the chain and gives it no value yet; the section Blocks and scope explains why it has to be there.

The order of the tests matters

Because the first true test wins, each test in a chain silently assumes that every test above it was false. When the tests overlap, as ranges do, that assumption decides the answer. Here is the same chain with the tests written in the opposite order.

code/m03-decisions/BadOrder.java
public class BadOrder {
    public static void main(String[] args) {
        int score = 85;
        String grade;
        if (score >= 40) {
            grade = "Pass";
        } else if (score >= 50) {
            grade = "Merit";
        } else if (score >= 70) {
            grade = "Distinction";
        } else {
            grade = "Fail";
        }
        System.out.println("Score " + score + ": " + grade);
    }
}
Terminal, in code/m03-decisions
> javac BadOrder.java
> java BadOrder
Score 85: Pass

It compiled without a murmur and gave the wrong grade. Trace it the way Java does:

StepTestWith score = 85What happens
1score >= 40truegrade becomes "Pass". The chain ends here.
2 and 3never reachedThe two remaining tests, and the else block, are skipped.

The mistake is worse than one wrong answer. Any score of 50 or more is also 40 or more, so the "Merit" and "Distinction" blocks can never run for any score at all. The compiler does not mind: it does not work out whether a condition can ever be true.

The rule for a range chain: write the tests from the most demanding to the least when you use >= (highest threshold first, as in GradeChain), or from the smallest to the largest when you use <. Then when a test is reached, the earlier ones have already ruled out everything that would have overlapped.

Predict

These two programs have the same three tests. In the first they are separate if statements. In the second they are joined with else if. With score equal to 85, what does each print?

code/m03-decisions/predict/SeparateIfs.java (lines 3 to 12)
int score = 85;
if (score >= 70) {
    System.out.println("Distinction");
}
if (score >= 50) {
    System.out.println("Merit");
}
if (score >= 40) {
    System.out.println("Pass");
}
code/m03-decisions/predict/JoinedIfs.java (lines 3 to 10)
int score = 85;
if (score >= 70) {
    System.out.println("Distinction");
} else if (score >= 50) {
    System.out.println("Merit");
} else if (score >= 40) {
    System.out.println("Pass");
}
Reveal the answer
Terminal, in code/m03-decisions/predict
> javac SeparateIfs.java JoinedIfs.java
> java SeparateIfs
Distinction
Merit
Pass
> java JoinedIfs
Distinction

The first prints all three lines, the second only Distinction. Separate if statements are independent questions: each condition is tested on its own, and 85 passes all three. In a chain, a later test is only reached if every earlier one failed. Use separate ifs when the outcomes can all apply together, and a chain when exactly one outcome should be chosen.

The second program also has no final else, so a score below 40 would print nothing at all. That is allowed; just be sure it is what you intend.

Blocks and scope

Every pair of braces makes a block, and a variable declared inside a block belongs to that block. The part of the program where a name can be used is its scope. A variable's scope starts at its declaration and ends at the closing brace of the block it was declared in. After that brace the name does not exist.

code/m03-decisions/broken/ScopeLost.java
public class ScopeLost {
    public static void main(String[] args) {
        int temperature = 4;
        if (temperature < 5) {
            String advice = "Take a coat.";
        }
        System.out.println(advice);
    }
}
Terminal, in code/m03-decisions/broken
> javac ScopeLost.java
ScopeLost.java:7: error: cannot find symbol
        System.out.println(advice);
                           ^
  symbol:   variable advice
  location: class ScopeLost
1 error

This is the cannot find symbol error from lesson 1, and the extra lines tell you which name: variable advice. Nothing is misspelt. The name was real on line 5, but the block that held it ended on line 6, and by line 7 there is nothing called advice. Reading the message literally, as lesson 1 advised, gets you to the cause.

main { ... } int temperature String advice visible from their declaration to the end of main if (temperature < 5) { ... } int degreesBelow exists only between these braces and can also use the outer variables

The rule is one-directional. Code inside a block can use the variables of the blocks around it, as the arrow shows. Code outside a block cannot see in. The fix for ScopeLost is to declare the variable before the block, in the larger scope, and only assign to it inside:

code/m03-decisions/ScopeFixed.java
public class ScopeFixed {
    public static void main(String[] args) {
        int temperature = 4;
        String advice = "No coat needed.";
        if (temperature < 5) {
            int degreesBelow = 5 - temperature;
            advice = "Take a coat. It is " + degreesBelow + " below five.";
        }
        System.out.println(advice);
    }
}
Terminal, in code/m03-decisions
> javac ScopeFixed.java
> java ScopeFixed
Take a coat. It is 1 below five.

advice is declared on line 4, in main, so it survives the if block. degreesBelow is declared on line 6 for use inside the block only, which is the right choice for a value nobody needs afterwards. Inside the block both are usable, and so is temperature.

Branches and definite assignment

Lesson 2 introduced the error might not have been initialized: a local variable must be given a value on every path before it is read. A decision is where that rule bites. Suppose advice is declared without a value and assigned in the branches:

code/m03-decisions/broken/NotAssigned.java
public class NotAssigned {
    public static void main(String[] args) {
        int temperature = 4;
        String advice;
        if (temperature < 5) {
            advice = "Take a coat.";
        } else if (temperature >= 5) {
            advice = "No coat needed.";
        }
        System.out.println(advice);
    }
}
Terminal, in code/m03-decisions/broken
> javac NotAssigned.java
NotAssigned.java:10: error: variable advice might not have been initialized
        System.out.println(advice);
                           ^
1 error

To a person, the two conditions temperature < 5 and temperature >= 5 cover every number. The compiler does not work through your arithmetic like that. It reads the shape of the code, sees an if and an else if with no plain else, and concludes that there is a path where neither block runs and advice is never set. The cure is to end the chain with an else, which makes one of the branches certain to run:

code/m03-decisions/AllBranches.java (lines 4 to 10)
String advice;
if (temperature < 5) {
    advice = "Take a coat.";
} else {
    advice = "No coat needed.";
}
System.out.println(advice);
Terminal, in code/m03-decisions
> javac AllBranches.java
> java AllBranches
Take a coat.

This is also why GradeChain ends in else. A chain whose last branch is an unconditional else assigns the variable on every path, provided every branch assigns it, and the compiler accepts it.

Combining conditions

Real questions are rarely single comparisons. Is the visitor an adult and holding a ticket? needs two comparisons joined. You can join conditions with the three logical operators below, which take boolean values and produce a boolean.

OperatorNameTrue when
a && bandboth a and b are true
a || borat least one of a and b is true (both is fine)
!anota is false

The tables below list every possible combination, which is possible because each input has only two values. Such a table is called a truth table.

aba && ba || b
truetruetruetrue
truefalsefalsetrue
falsetruefalsetrue
falsefalsefalsefalse
a!a
truefalse
falsetrue

The program below prints the same tables. The parentheses around each && and || expression are needed because + binds more tightly than they do; without them Java would try to join the text and a boolean first and then apply && to the result. The two ! lines need none, because ! binds more tightly than +.

code/m03-decisions/TruthTables.java (lines 3 to 14)
System.out.println("true  && true  is " + (true && true));
System.out.println("true  && false is " + (true && false));
System.out.println("false && true  is " + (false && true));
System.out.println("false && false is " + (false && false));
System.out.println();
System.out.println("true  || true  is " + (true || true));
System.out.println("true  || false is " + (true || false));
System.out.println("false || true  is " + (false || true));
System.out.println("false || false is " + (false || false));
System.out.println();
System.out.println("!true  is " + !true);
System.out.println("!false is " + !false);
Terminal, in code/m03-decisions
> javac TruthTables.java
> java TruthTables
true  && true  is true
true  && false is false
false && true  is false
false && false is false

true  || true  is true
true  || false is true
false || true  is true
false || false is false

!true  is false
!false is true

Remember && as everything must hold and || as something must hold. A natural-language or often means one or the other but not both; Java's || does not exclude the case where both are true.

code/m03-decisions/Entry.java (lines 3 to 7)
int age = 20;
boolean hasTicket = false;
boolean isMember = true;
boolean canEnter = age >= 18 && (hasTicket || isMember);
System.out.println("Can enter: " + canEnter);
Terminal, in code/m03-decisions
> javac Entry.java
> java Entry
Can enter: true

Line 6 reads: the visitor is at least 18, and either has a ticket or is a member. The parentheses group the || so that it is decided first. This visitor has no ticket but is a member, so (hasTicket || isMember) is true, and with the age condition also true the whole thing is true.

Short-circuit evaluation

Java evaluates && and || from left to right and stops as soon as the answer is certain. This is called short-circuit evaluation. If the left side of && is false, the result must be false whatever the right side says, so the right side is not evaluated at all. If the left side of || is true, the result must be true, and again the right side is skipped.

That is more than a speed-up. It lets you put a safety check on the left that protects the right. Here is a program that computes whether an average is above 5, with no check:

code/m03-decisions/NoGuard.java
public class NoGuard {
    public static void main(String[] args) {
        int count = 0;
        int total = 0;
        if (total / count > 5) {
            System.out.println("High average.");
        } else {
            System.out.println("No high average.");
        }
    }
}
Terminal, in code/m03-decisions
> javac NoGuard.java
> java NoGuard
Exception in thread "main" java.lang.ArithmeticException: / by zero
	at NoGuard.main(NoGuard.java:5)

It compiled, and then failed at run time: count is 0, and a whole number cannot be divided by zero. This is the exception from lesson 1, and the at line points at line 5, the condition. Now put a guard on the left of an &&:

code/m03-decisions/Guarded.java
public class Guarded {
    public static void main(String[] args) {
        int count = 0;
        int total = 0;
        if (count != 0 && total / count > 5) {
            System.out.println("High average.");
        } else {
            System.out.println("No high average.");
        }
    }
}
Terminal, in code/m03-decisions
> javac Guarded.java
> java Guarded
No high average.

count != 0 is false, so && already knows the answer and never evaluates total / count. The program takes the else branch. Swap the two halves and you are back to the crash, because the division would then run first. The order of the operands of && and || is part of the logic. The same trick works the other way with ||: count == 0 || total / count <= 5 is also safe.

You can watch the skipping happen by giving the right-hand side a visible effect. The ++calls below adds one to calls every time it is evaluated. Doing this in real code is poor style, since conditions should only ask questions; here it is a probe.

code/m03-decisions/SideEffect.java (lines 3 to 7)
int calls = 0;
boolean first = 5 > 3 || ++calls > 0;
System.out.println("first = " + first + ", calls = " + calls);
boolean second = 5 < 3 || ++calls > 0;
System.out.println("second = " + second + ", calls = " + calls);
Terminal, in code/m03-decisions
> javac SideEffect.java
> java SideEffect
first = true, calls = 0
second = true, calls = 1

In the first line, 5 > 3 is true, so || is done and ++calls never ran: calls is still 0. In the second, 5 < 3 is false, so || had to look at the right side, and calls became 1.

Precedence and parentheses

When one expression has several operators, Java applies them in a fixed order, as it does for * before +. From tightest to loosest, the operators in this lesson rank like this:

  1. !
  2. arithmetic: * / %, then + -
  3. comparisons: < > <= >=, then == !=
  4. &&
  5. ||
  6. the conditional operator ? :, met later in this lesson
  7. assignment: =, += and the others from lesson 2

So age + 1 >= 18 && age < 65 needs no parentheses: the arithmetic happens first, then the comparisons, and last the &&. The pair that surprises people is && and ||.

Predict

What do the first three lines print? (The fourth is the age + 1 >= 18 && age < 65 example above, with age equal to 17.)

code/m03-decisions/predict/Precedence.java (lines 3 to 7)
System.out.println(true || false && false);
System.out.println((true || false) && false);
System.out.println(!true || true);
int age = 17;
System.out.println(age + 1 >= 18 && age < 65);
Reveal the answer
Terminal, in code/m03-decisions/predict
> javac Precedence.java
> java Precedence
true
false
true
true

The output is true, false, true, true. In the first line && goes before ||, so Java reads true || (false && false), which is true || false, which is true. The second line forces the || first: true && false is false. In the third, ! applies only to the true next to it, giving false || true, which is true; had ! applied to the whole expression the answer would have been false. The fourth is true because 17 + 1 is 18, and 17 is below 65.

Having the rules is not the same as relying on them. Mixed && and || in one expression forces every reader, including you next month, to recall the precedence. Add parentheses whenever you mix the two, even where the compiler does not need them: a || (b && c) says what it means.

De Morgan's laws: negating a condition

Sometimes you have a condition and need its opposite, for example to write the else logic, or to flip valid into invalid. Putting ! in front of the whole expression always works, but !(x >= 4 && x <= 10) is harder to read than the plain version. De Morgan's laws say how to push the ! inside:

In words: not (this and that) means not this, or not that. A truth table proves the first law by listing every case; the two columns that matter are identical.

aba && b!(a && b)!a!b!a || !b
truetruetruefalsefalsefalsefalse
truefalsefalsetruefalsetruetrue
falsetruefalsetruetruefalsetrue
falsefalsefalsetruetruetruetrue

The second law has the same shape with the operators swapped; draw its table yourself as practice. In practice you usually want to negate each comparison as you push the ! in, which makes the ! disappear altogether. The negation of each comparison is its opposite: >= becomes <, <= becomes >, == becomes !=. Note that the opposite of >= is <, not <=. The program below checks one rewrite on three values.

code/m03-decisions/DeMorgan.java (lines 3 to 8)
int x = 7;
int y = 2;
int z = 12;
System.out.println("x = " + x + "  negated: " + !(x >= 4 && x <= 10) + "  rewritten: " + (x < 4 || x > 10));
System.out.println("y = " + y + "  negated: " + !(y >= 4 && y <= 10) + "  rewritten: " + (y < 4 || y > 10));
System.out.println("z = " + z + "  negated: " + !(z >= 4 && z <= 10) + "  rewritten: " + (z < 4 || z > 10));
Terminal, in code/m03-decisions
> javac DeMorgan.java
> java DeMorgan
x = 7  negated: false  rewritten: false
y = 2  negated: true  rewritten: true
z = 12  negated: true  rewritten: true

On each line the two forms agree. Not between 4 and 10 was written as !(x >= 4 && x <= 10) and as x < 4 || x > 10: the && became ||, and each comparison was flipped. Three values do not prove a law, but the truth table above does, and the program is a useful habit: when you rewrite a condition, test old and new on values from each region.

Checking a range

In mathematics you write 0 ≤ x ≤ 10. Java will not accept it:

code/m03-decisions/broken/ChainedRange.java
public class ChainedRange {
    public static void main(String[] args) {
        int x = 5;
        if (0 <= x <= 10) {
            System.out.println("x is between 0 and 10");
        }
    }
}
Terminal, in code/m03-decisions/broken
> javac ChainedRange.java
ChainedRange.java:4: error: bad operand types for binary operator '<='
        if (0 <= x <= 10) {
                   ^
  first type:  boolean
  second type: int
1 error

The message tells you what happened. Java evaluates 0 <= x first, which gives a boolean, and then tries to compare that with 10 using <=. A boolean cannot be compared with a number, so the operator has the wrong types. The error shows both types: boolean on the left, int on the right. To check a range, write two comparisons and join them. Inside the range is an &&; outside it is an ||:

code/m03-decisions/Range.java (lines 3 to 9)
int x = 5;
if (0 <= x && x <= 10) {
    System.out.println("x is between 0 and 10");
}
if (x < 0 || x > 10) {
    System.out.println("x is outside 0 to 10");
}
Terminal, in code/m03-decisions
> javac Range.java
> java Range
x is between 0 and 10

Notice the shape. Inside means above the lower bound and below the upper one, so both must hold. Outside means below the lower bound or above the upper one, so one is enough. Using && for outside, which would read x < 0 && x > 10, is a classic mistake: no number is both below 0 and above 10, so it is never true.

Mistakes the compiler will not catch

The errors so far came with a message. The mistakes below are legal Java, so javac says nothing, and the program runs and gives wrong results. You have to learn to see them.

A semicolon after the condition

Predict

With temperature equal to 20, the coat message should not appear. Look closely at line 4. What does this program print?

code/m03-decisions/predict/SemicolonAfterIf.java
public class SemicolonAfterIf {
    public static void main(String[] args) {
        int temperature = 20;
        if (temperature < 5);
        {
            System.out.println("Take a coat.");
        }
        System.out.println("Have a good day.");
    }
}
Reveal the answer
Terminal, in code/m03-decisions/predict
> javac SemicolonAfterIf.java
> java SemicolonAfterIf
Take a coat.
Have a good day.

Both lines, and javac printed nothing. The semicolon ends the if statement right there. An if may be followed by a single statement, and ; by itself is a legal statement that does nothing, so the if controls an empty body. The braces on the next lines are then a plain block, which is allowed anywhere a statement is, and a plain block always runs. The program does exactly what it was written to do, which is not what was meant. If an if seems to ignore its condition, check the end of its line for a semicolon.

Missing braces

When there are no braces after the condition, the if controls exactly one statement: the next one. Indentation is for humans and has no effect on this.

code/m03-decisions/MissingBraces.java (lines 3 to 7)
int temperature = 20;
if (temperature < 5)
    System.out.println("Take a coat.");
    System.out.println("Bring a scarf.");
System.out.println("Have a good day.");
Terminal, in code/m03-decisions
> javac MissingBraces.java
> java MissingBraces
Bring a scarf.
Have a good day.

Line 6 is indented like line 5, and a reader assumes both belong to the if. They do not. At 20 degrees the coat line was correctly skipped, but Bring a scarf. ran unconditionally. The cure is the habit this course follows: always write the braces, even for a single statement. Then adding a second line later cannot go wrong.

Comparing double values with ==

Lesson 2 showed that double arithmetic is not exact: values like 0.1 cannot be stored precisely. That matters the moment you compare:

code/m03-decisions/FloatEquals.java (lines 3 to 9)
double sum = 0.1 + 0.2;
System.out.println(sum == 0.3);
System.out.println(sum);

System.out.println(Math.abs(-3.5));
double difference = Math.abs(sum - 0.3);
System.out.println(difference < 0.000001);
Terminal, in code/m03-decisions
> javac FloatEquals.java
> java FloatEquals
false
0.30000000000000004
3.5
true

Mathematically 0.1 + 0.2 is 0.3, but sum == 0.3 is false, because the stored sum is 0.30000000000000004. == demands that the two values be exactly equal. The usual approach is to test whether the values are close enough: subtract, discard the sign, and compare the difference with a small tolerance. Math.abs(x) is a ready-made method from the standard library that gives x without its minus sign, so Math.abs(-3.5) is 3.5. It is called with a name, a dot and parentheses, as println is; lesson 5 shows how methods like it are built. How small the tolerance should be depends on the problem. One that suits the data is better than any fixed rule.

For whole numbers (int, long, char) == is exact and fine. The trouble is specific to double values that came out of arithmetic.

Comparing text

To check whether a String holds particular text, use the .equals method:

code/m03-decisions/SameName.java (lines 3 to 9)
String name = "Ada";
if (name.equals("Ada")) {
    System.out.println("Hello, Ada.");
} else {
    System.out.println("Who are you?");
}
System.out.println(name.equals("ada"));
Terminal, in code/m03-decisions
> javac SameName.java
> java SameName
Hello, Ada.
false

name.equals("Ada") is a method call like System.out.println(...), with a dot, a name and parentheses. It asks the text in name whether it has the same characters as "Ada", and answers with a boolean, so it can sit directly in an if. The comparison is case-sensitive: the last line shows that "Ada" and "ada" are different.

The rule for now: compare strings with .equals(...), never with ==. The reason needs ideas about how Java stores objects, which come in lesson 6, where it is explained properly. For now take the rule on trust, but see why it matters. The compiler accepts == between strings without complaint, and it can even appear to work:

code/m03-decisions/StringTrap.java (lines 3 to 9)
String literal = "Ada";
String start = "Ad";
String built = start + "a";

System.out.println(literal == "Ada");
System.out.println(built == "Ada");
System.out.println(built.equals("Ada"));
Terminal, in code/m03-decisions
> javac StringTrap.java
> java StringTrap
true
false
true

The first line used == on a plain literal and gave true. The second used == on a string that was assembled while the program ran from "Ad" and "a", which holds exactly the same characters, and gave false. The third used .equals on that same string and gave the right answer. A comparison that works in one test and fails in another is the worst kind of bug, so .equals is the only form to use until lesson 6 tells you more.

The conditional operator

Often an if/else exists only to pick one of two values. Java has a compact form for that, the conditional operator, also called the ternary operator because it is the only one that takes three parts:

condition ? valueIfTrue : valueIfFalse

It is an expression, not a statement: the whole thing has a value, so it can be assigned, printed or joined to text. If the condition is true the value is the one after the ?; otherwise it is the one after the :.

code/m03-decisions/Ternary.java (lines 3 to 11)
int age = 20;
String label = age >= 18 ? "adult" : "minor";
System.out.println("Label: " + label);

int a = 12;
int b = 9;
System.out.println("Larger: " + (a > b ? a : b));
int items = 1;
System.out.println("You have " + items + (items == 1 ? " item" : " items") + ".");
Terminal, in code/m03-decisions
> javac Ternary.java
> java Ternary
Label: adult
Larger: 12
You have 1 item.

Each use picks a value, and nothing more. Because ?: ranks below + in the precedence list, a conditional joined into text needs its own parentheses, as lines 9 and 11 have.

The conditional operator helps when the choice is small, as above: one condition, two short values. It hurts when you nest it:

code/m03-decisions/NestedTernary.java
public class NestedTernary {
    public static void main(String[] args) {
        int score = 85;
        String grade = score >= 70 ? "Distinction" : score >= 50 ? "Merit" : score >= 40 ? "Pass" : "Fail";
        System.out.println(grade);
    }
}
Terminal, in code/m03-decisions
> javac NestedTernary.java
> java NestedTernary
Distinction

This does work and prints the same answer as GradeChain, but compare how you read it. The else if chain puts one decision on each line; this puts three on one line and makes you count colons. Use ?: for one choice between two values, and an if chain for anything bigger, or anything that does more than choose a value. One more constraint: both possible values must suit where the result is going.

code/m03-decisions/broken/TernaryTypes.java
public class TernaryTypes {
    public static void main(String[] args) {
        boolean found = true;
        int result = found ? 1 : "none";
        System.out.println(result);
    }
}
Terminal, in code/m03-decisions/broken
> javac TernaryTypes.java
TernaryTypes.java:4: error: incompatible types: bad type in conditional expression
        int result = found ? 1 : "none";
                                 ^
    String cannot be converted to int
1 error

Here result is an int, so both choices must be numbers. The message names the choice that is not: String cannot be converted to int.

switch: choosing between many exact values

A chain of ifs can test anything. When what you are really doing is comparing one value against a list of exact possibilities, Java offers a tidier tool, switch. It comes in two forms. The classic form dates from Java's beginning and you will meet it in older code. The arrow form arrived in Java 14 and is the better one to write. You need to read both.

The classic form

code/m03-decisions/PolygonName.java (lines 3 to 20)
int sides = 5;
switch (sides) {
    case 3:
        System.out.println("triangle");
        break;
    case 4:
        System.out.println("quadrilateral");
        break;
    case 5:
        System.out.println("pentagon");
        break;
    case 6:
        System.out.println("hexagon");
        break;
    default:
        System.out.println("some other polygon");
}
System.out.println("Done.");
Terminal, in code/m03-decisions
> javac PolygonName.java
> java PolygonName
pentagon
Done.

The expression in parentheses, here sides, is evaluated once. Java then looks for a case label equal to its value, starting at the top. When it finds one, it runs the statements after that label, and carries on through the statements below until it reaches a break or the closing brace of the switch. A break jumps out of the switch to the first statement after it, which is why Done. appears once. The default label is the catch-all: it is used when no case matches. It is last here, so it needs no break.

default is optional in a switch statement like this one. When nothing matches and there is no default, nothing happens:

code/m03-decisions/NoDefault.java (lines 3 to 12)
int sides = 7;
switch (sides) {
    case 3:
        System.out.println("triangle");
        break;
    case 4:
        System.out.println("quadrilateral");
        break;
}
System.out.println("Done.");
Terminal, in code/m03-decisions
> javac NoDefault.java
> java NoDefault
Done.

Fall-through

Look again at the sentence that says Java carries on after a match. Nothing in a classic switch stops at the next label by itself. That is the source of its best-known bug.

Predict

Here sides is 4, and the break after the "quadrilateral" line has been forgotten. What is printed?

code/m03-decisions/predict/FallThrough.java (lines 3 to 18)
int sides = 4;
switch (sides) {
    case 3:
        System.out.println("triangle");
        break;
    case 4:
        System.out.println("quadrilateral");
    case 5:
        System.out.println("pentagon");
        break;
    case 6:
        System.out.println("hexagon");
        break;
    default:
        System.out.println("some other polygon");
}
Reveal the answer
Terminal, in code/m03-decisions/predict
> javac FallThrough.java
> java FallThrough
quadrilateral
pentagon

Two lines: quadrilateral and then pentagon. The label case 4: matched, and Java ran its statement. With no break to leave the switch, it carried straight on into the statements under case 5: without testing that label, and stopped at the break after "pentagon". This behaviour is called fall-through. The compiler does not report it, because it can be written on purpose.

Doing it on purpose is how classic switches share one block between several labels. An empty case falls through to the next, so a list of labels in a row all end up at the same statements:

code/m03-decisions/VowelCheck.java (lines 3 to 14)
char letter = 'e';
switch (letter) {
    case 'a':
    case 'e':
    case 'i':
    case 'o':
    case 'u':
        System.out.println(letter + " is a vowel");
        break;
    default:
        System.out.println(letter + " is not a vowel");
}
Terminal, in code/m03-decisions
> javac VowelCheck.java
> java VowelCheck
e is a vowel

This program also shows that you can switch on a char: the labels are char literals in single quotes. If you ever write fall-through deliberately in older-style code, add a comment saying so; otherwise the next reader cannot tell it from a forgotten break.

What a switch can test

You can switch on an int, on a char and on a String. For a String, a label matches when the text is the same, as with .equals:

code/m03-decisions/CommandSwitch.java (lines 3 to 16)
String command = "stop";
switch (command) {
    case "go":
        System.out.println("Moving.");
        break;
    case "stop":
        System.out.println("Halting.");
        break;
    case "wait":
        System.out.println("Pausing.");
        break;
    default:
        System.out.println("Unknown command: " + command);
}
Terminal, in code/m03-decisions
> javac CommandSwitch.java
> java CommandSwitch
Halting.

You cannot switch on a double. The same is true of long and boolean; if handles those.

code/m03-decisions/broken/SwitchDouble.java
public class SwitchDouble {
    public static void main(String[] args) {
        double price = 2.5;
        switch (price) {
            case 2.5:
                System.out.println("two and a half");
                break;
            default:
                System.out.println("something else");
        }
    }
}
Terminal, in code/m03-decisions/broken
> javac SwitchDouble.java
SwitchDouble.java:4: error: primitive patterns are a preview feature and are disabled by default.
        switch (price) {
               ^
  (use --enable-preview to enable primitive patterns)
1 error

The wording depends on the Java version. Java 27 mentions a preview feature because the language designers are experimenting with allowing such switches; without that experimental option, which you should not turn on, the switch is refused. Either way the rule for you is the same: of the types you have met, a switch accepts int, char and String (a few other types, such as enums, come later in the course).

The labels must also be constants: literal values, or final variables that you initialise on the line that declares them with a literal or another fixed value. An ordinary variable will not do, because a label is a fixed value that has to be known while the program is being compiled:

code/m03-decisions/broken/CaseVariable.java
public class CaseVariable {
    public static void main(String[] args) {
        int target = 3;
        int sides = 3;
        switch (sides) {
            case target:
                System.out.println("hit");
                break;
            default:
                System.out.println("miss");
        }
    }
}
Terminal, in code/m03-decisions/broken
> javac CaseVariable.java
CaseVariable.java:6: error: constant expression required
            case target:
                 ^
1 error

Making the variable a final constant, as lesson 2 showed (here named TARGET, in capitals), and writing case TARGET:, turns the same program into a legal one:

code/m03-decisions/CaseConstant.java (lines 3 to 11)
final int TARGET = 3;
int sides = 3;
switch (sides) {
    case TARGET:
        System.out.println("hit");
        break;
    default:
        System.out.println("miss");
}
Terminal, in code/m03-decisions
> javac CaseConstant.java
> java CaseConstant
hit

The arrow form

Java 14 added a form of switch that removes the two awkward parts of the classic one. It replaces the colon after a label with an arrow, ->. Each arrow runs one statement, or a block in braces, and then the switch is finished: there is no fall-through and no break. A single case can also list several labels separated by commas, which replaces the stacked empty cases.

code/m03-decisions/ArrowDays.java (lines 3 to 12)
int day = 6;
switch (day) {
    case 1, 2, 3, 4, 5 -> System.out.println("Weekday");
    case 6, 7 -> {
        System.out.println("Weekend");
        System.out.println("Time to rest.");
    }
    default -> System.out.println("Not a day number");
}
System.out.println("Done.");
Terminal, in code/m03-decisions
> javac ArrowDays.java
> java ArrowDays
Weekend
Time to rest.
Done.

With day equal to 6, the label list 6, 7 matched. Only its block ran: the Weekday line above it and the default line below it did not, and nothing had to stop them. Compare case 6, 7 -> with the five stacked lines of VowelCheck.

switch as an expression

The arrow form has a second capability, and it is the main reason to prefer it. A switch can be an expression: the whole thing produces a value, which you can assign to a variable.

code/m03-decisions/SwitchExpr.java (lines 3 to 9)
int day = 6;
String kind = switch (day) {
    case 1, 2, 3, 4, 5 -> "weekday";
    case 6, 7 -> "weekend";
    default -> "not a day number";
};
System.out.println("Day " + day + ": " + kind);
Terminal, in code/m03-decisions
> javac SwitchExpr.java
> java SwitchExpr
Day 6: weekend

The value to the right of each arrow becomes the value of the whole switch when that case is chosen. Three details are worth noticing. The switch sits on the right of an =. There is a semicolon after its closing brace, because it is an expression that ends a declaration statement. And there is no way to forget to assign kind: every route through the switch must produce a value, and the compiler enforces it.

That last point has a consequence. A switch expression must cover every possible value of what it switches on. For an int that means a default, because the compiler cannot list every possible int:

code/m03-decisions/broken/NotExhaustive.java
public class NotExhaustive {
    public static void main(String[] args) {
        int day = 6;
        String kind = switch (day) {
            case 1, 2, 3, 4, 5 -> "weekday";
            case 6, 7 -> "weekend";
        };
        System.out.println(kind);
    }
}
Terminal, in code/m03-decisions/broken
> javac NotExhaustive.java
NotExhaustive.java:4: error: the switch expression does not cover all possible input values
        String kind = switch (day) {
                      ^
  missing patterns:
      int _
1 error

The message here adds a missing patterns detail that is not important at this stage. The first line says what is wrong, and the fix is a default case, as in SwitchExpr. Without one, a day number of 9 would leave kind with no value, which is the same problem as might not have been initialized seen from another side.

One more error belongs to both forms. A value may appear in only one label:

code/m03-decisions/broken/DupCase.java
public class DupCase {
    public static void main(String[] args) {
        int day = 6;
        switch (day) {
            case 1, 2, 3, 4, 5 -> System.out.println("Weekday");
            case 5, 6, 7 -> System.out.println("Weekend");
            default -> System.out.println("Not a day number");
        }
    }
}
Terminal, in code/m03-decisions/broken
> javac DupCase.java
DupCase.java:6: error: duplicate case label
            case 5, 6, 7 -> System.out.println("Weekend");
            ^
1 error

Day 5 is listed in both case lines, so it is unclear which should win. The compiler refuses to guess and points at the line of the second one.

Ranges with a switch

A switch compares for equality, so it has no way to say 70 or above. There are two ways to handle ranges. One is to list every value, as case 1, 2, 3, 4, 5 does above; that is practical for a handful of values and absurd for a hundred. The other is to switch on a value computed from the original so that each range turns into one number. Integer division from lesson 2 does exactly that: dividing by 10 maps 0 to 9 onto 0, 10 to 19 onto 1, and so on.

code/m03-decisions/SwitchRange.java (lines 3 to 15)
int score = 85;
if (score < 0 || score > 100) {
    System.out.println("Score must be from 0 to 100.");
} else {
    String grade = switch (score / 10) {
        case 10, 9 -> "A";
        case 8 -> "B";
        case 7 -> "C";
        case 6 -> "D";
        default -> "F";
    };
    System.out.println("Score " + score + ": grade " + grade);
}
Terminal, in code/m03-decisions
> javac SwitchRange.java
> java SwitchRange
Score 85: grade B

85 divided by 10 is 8, so case 8 was chosen. A score of 100 gives 10, and case 10, 9 handles it along with the nineties. Every score from 0 to 59 gives a number from 0 to 5 and lands in default. The if on top is not decoration: without it, a score of 105 would divide to 10 and be graded A. The trick also stops working as soon as the ranges are not the same width. For ranges of unequal size, an if chain is the better tool.

Choosing between if and switch

Use a switch whenUse an if chain when
you compare one value with a list of exact constantsthe conditions involve different variables, or combine several tests with && and ||
several labels share the same result (case 6, 7 ->)you need ranges (score >= 70) of uneven size
you want the compiler to insist that every value is handled (switch expression)the condition is a boolean, or a comparison like != or <
the labels are text commands or char codesthere are only two outcomes

Neither is better in general. A switch says this is a choice between listed cases; an if chain says work down these tests in order. Choose the one whose shape matches the decision.

Exercises

Each exercise has a folder waiting in work/m03-decisions/ in your course kit. Compile and run from the terminal, inside the exercise's folder. Open a hint only after a real attempt. Several exercises ask for a written answer; those count as much as the code.

warm-up

Exercise 3.1 · Prediction worksheet

Work in work/m03-decisions/ex1-prediction-worksheet/ in your course kit

Your folder contains Worksheet.java and predictions.md. Do not compile or run the program yet. Read it, work out by hand what each of the 14 output lines labelled 1: to 14: will print and what calls will be at the end, and write your predictions in the table in predictions.md. (The labels are part of the program's output. They are not the line numbers of the source file.) Only then compile and run, fill in the actual column, and answer the four questions under the table.

work/m03-decisions/ex1-prediction-worksheet/Worksheet.java
public class Worksheet {
    public static void main(String[] args) {
        int a = 6;
        int b = 0;
        boolean ready = true;
        boolean paid = false;
        int calls = 0;

        System.out.println("1: " + (a > 5 && ready));
        System.out.println("2: " + (a > 5 && paid));
        System.out.println("3: " + (a == 6 || paid));
        System.out.println("4: " + !ready);
        System.out.println("5: " + (!ready || paid));
        System.out.println("6: " + !(ready || paid));
        System.out.println("7: " + (ready || paid && !ready));
        System.out.println("8: " + ((ready || paid) && !ready));
        System.out.println("9: " + (b != 0 && a / b > 1));
        System.out.println("10: " + (b == 0 || a / b > 1));
        System.out.println("11: " + (paid && ++calls > 0));
        System.out.println("12: " + (ready && ++calls > 0));
        System.out.println("13: " + (ready || ++calls > 0));
        System.out.println("14: " + (paid || ++calls > 5));
        System.out.println("calls = " + calls);
    }
}

A few predictions will be wrong the first time; that is expected and is the useful part. Do not change the program, only your table.

Hint 1

Work on one line at a time, and write down the value of each side of every && or || before combining them. For the output lines labelled 11: to 14:, ask first whether the right-hand side is evaluated at all.

Hint 2

If the lines labelled 7: and 8: confuse you, put in your own brackets showing which operator Java applies first, using the precedence list in the section Combining conditions.

To check it, run python check.py m03 ex1 in your course kit folder.

warm-up

Exercise 3.2 · Pool price

Work in work/m03-decisions/ex2-pool-price/ in your course kit

Write PoolPrice.java (class PoolPrice). Declare int age = 20; and boolean student = true; at the top of main. A swimming pool charges whole pounds according to these rules:

  • under 5: 0
  • 5 to 15 inclusive: 3
  • 65 or over: 3
  • students aged 25 or under (who are not already covered above): 4
  • everyone else: 6

Print the two lines shown below. Constraints: use one if / else if / else chain with no nested if, set an int price in the branches, print it only once, and use && in the student test.

Output of java PoolPrice
Age 20, student: true
Price: 4 pounds

Then change the starting values and test the edges of every rule: ages 4, 5, 15, 16, 25, 26 and 65, with student both true and false.

Hint 1

A student aged 12 pays 3, not 4. Decide which test has to come first so that this is true without extra conditions.

Hint 2

If one of your boundaries is wrong, check whether you wrote < where the rule says inclusive or or over and needs <= or >=.

To check it, run python check.py m03 ex2 in your course kit folder.

core

Exercise 3.3 · Leap years

Work in work/m03-decisions/ex3-leap-years/ in your course kit

Write LeapYear.java (class LeapYear) with int year = 2100; at the top of main. A year is a leap year if it is divisible by 4, except that years divisible by 100 are not leap years, unless they are also divisible by 400. (So 1900 is not a leap year, and 2000 is.)

  • Compute the answer as one expression assigned to a boolean leap, using %, &&, || and parentheses where they make the meaning clear. No nested ifs.
  • Then use a single if/else on leap to print one sentence: 2100 is a leap year when leap is true and 2100 is not a leap year when it is false (with your own value of year in place of 2100). The sample run below is for 2100.
Output of java LeapYear
2100 is not a leap year

Your folder contains test-log.md. Work out by hand which of the six listed years are leap years, then run your program on each and record the result, and answer the question at the end.

Hint 1

Say the rule as two alternatives joined by or: divisible by 400, or divisible by 4 and not by 100. Each part becomes a comparison like year % 4 == 0.

Hint 2

If 1900 or 2000 comes out wrong in your log, trace the expression by hand for that year, writing the true or false value under each comparison.

To check it, run python check.py m03 ex3 in your course kit folder.

core

Exercise 3.4 · Thermostat bug log

Work in work/m03-decisions/ex4-bug-log/ in your course kit

Your folder contains Thermostat.java, which compiles but prints the wrong thing, and bug-log.md. It contains three mistakes of the kind described in the section Mistakes the compiler will not catch and the section switch. With the starting values it should print exactly these three lines:

Correct output of java Thermostat
Temperature: 21
Mode: comfort
Check finished.

Compile and run the starter first and compare. Then, for each of the three bugs, find it, write an entry in bug-log.md (where it is, what extra output it caused, why Java behaved that way in your own words, and what you changed), and fix it. Do not delete any of the thermostat's behaviour to make the output match. Finally, answer the three questions at the end of the log.

Hint 1

Each bug adds an extra line to the output. For each unwanted line, ask which statement printed it, and then what decides whether that statement runs.

Hint 2

After fixing everything, change the starting values (for example temperature = 15, windowOpen = true, mode = 3) and check that every part still behaves as its comment says.

To check it, run python check.py m03 ex4 in your course kit folder.

core

Exercise 3.5 · Seasons, twice

Work in work/m03-decisions/ex5-seasons-twice/ in your course kit

Write two programs that do the same job in different ways. Each declares int month = 12; and prints a line like the one below, using northern-hemisphere seasons: December to February winter, March to May spring, June to August summer, September to November autumn. A number that is not a month, such as 0 or 13, must print not a valid month in place of the season, for example Month 13: not a valid month.

  • SeasonIf.java: an if / else if / else chain with comparison operators and logical operators. No switch.
  • SeasonSwitch.java: an arrow-form switch expression assigned to a String, with several labels in one case. No if.
Output of java SeasonIf (first line), then of java SeasonSwitch (second line)
Month 12: winter
Month 12: winter

Test both on months 0, 1, 2, 3, 5, 6, 8, 9, 11, 12 and 13. Then answer the four questions in comparison.md.

Hint 1

December is the awkward one for the chain, because winter wraps round the end of the year. Think of winter as two pieces joined by or.

Hint 2

For the chain, test for an invalid month first. Then each later test can assume the month is between 1 and 12, which keeps the comparisons short. Winter is the exception: it still needs both of its pieces, as in Hint 1.

To check it, run python check.py m03 ex5 in your course kit folder.

stretch

Exercise 3.6 · Triangle types

Work in work/m03-decisions/ex6-triangle-types/ in your course kit

Write TriangleKind.java (class TriangleKind) with int a = 5;, int b = 5; and int c = 8; as the side lengths. Three lengths make a valid triangle when every side is greater than 0 and each pair of sides adds up to more than the third (a + b > c and the other two pairings).

  • Declare boolean invalid with one expression built from || that is true when the sides do not make a triangle.
  • Declare boolean valid with one expression built from && that is true when they do. Write it out; do not just write !invalid. This is De Morgan's laws in use.
  • Always print these two lines first, whether or not the triangle is valid: Sides: 5, 5, 8 (the three lengths, separated by a comma and a space) and Forms agree: followed by the result of valid == !invalid, which should be true for any sides you try.
  • Then, if the triangle is valid, print Valid: yes and a line Kind: followed by equilateral (all three sides equal), isosceles (exactly two equal) or scalene (none equal). If it is not valid, print only Valid: no after those first two lines.
Output of java TriangleKind
Sides: 5, 5, 8
Forms agree: true
Valid: yes
Kind: isosceles

Test it on 1, 2, 3 (invalid), 3, 3, 3 (equilateral), 3, 4, 5 (scalene) and 0, 4, 4 (invalid). Then fill in demorgan.md: copy your two expressions, explain how one turns into the other, and say which of the two you find easier to read and which you would rather have to debug.

Hint 1

Write invalid first. Then go through it part by part: each || turns into && and each comparison turns into its opposite. Remember the opposite of <= is >.

Hint 2

An equilateral triangle also has two equal sides. Think about which of the two tests has to be asked first so that equilateral triangles are not reported as isosceles. The section Making a choice has the rule about order.

To check it, run python check.py m03 ex6 in your course kit folder.

Summary

Words introduced in this lesson

TermMeaning
ConditionAn expression whose value is a boolean.
Comparison operatorOne of == != < > <= >=; compares two values and produces a boolean.
BlockStatements between a pair of braces.
ChainAn if followed by one or more else if parts and optionally a final else; the first true test wins.
ScopeThe part of a program where a variable's name can be used: from its declaration to the end of its block.
Logical operator&& (and), || (or) or ! (not).
Truth tableA table listing the result of a logical operation for every combination of inputs.
Short-circuit evaluation&& and || skip their right side when the left side already settles the result.
De Morgan's laws!(a && b) equals !a || !b, and !(a || b) equals !a && !b.
Conditional operatorcondition ? a : b, an expression that has the value a or b.
switchChooses between cases by comparing one value with constant labels.
Fall-throughIn a classic switch, continuing into the next case's statements because there was no break.
Switch expressionA switch that produces a value; it must cover every possible input.