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 ifchains, the conditional operator andswitchfor 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.
| Operator | Meaning | Example | Value when age is 17 |
|---|---|---|---|
== | is equal to | age == 17 | true |
!= | is not equal to | age != 17 | false |
< | is less than | age < 18 | true |
> | is greater than | age > 17 | false |
<= | is less than or equal to | age <= 17 | true |
>= | is greater than or equal to | age >= 18 | false |
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.
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);
}
}> 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:
public class AssignInIf {
public static void main(String[] args) {
int x = 3;
if (x = 5) {
System.out.println("x is five");
}
}
}> javac AssignInIf.java
AssignInIf.java:4: error: incompatible types: int cannot be converted to boolean
if (x = 5) {
^
1 errorAn 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:
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);
}
}> 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.
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.");
}
}> 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.
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.
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);
}
}> 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.
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);
}
}> 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.
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);
}
}> javac BadOrder.java > java BadOrder Score 85: Pass
It compiled without a murmur and gave the wrong grade. Trace it the way Java does:
| Step | Test | With score = 85 | What happens |
|---|---|---|---|
| 1 | score >= 40 | true | grade becomes "Pass". The chain ends here. |
| 2 and 3 | never reached | The 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.
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?
int score = 85;
if (score >= 70) {
System.out.println("Distinction");
}
if (score >= 50) {
System.out.println("Merit");
}
if (score >= 40) {
System.out.println("Pass");
}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
> 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.
public class ScopeLost {
public static void main(String[] args) {
int temperature = 4;
if (temperature < 5) {
String advice = "Take a coat.";
}
System.out.println(advice);
}
}> javac ScopeLost.java
ScopeLost.java:7: error: cannot find symbol
System.out.println(advice);
^
symbol: variable advice
location: class ScopeLost
1 errorThis 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.
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:
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);
}
}> 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:
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);
}
}> javac NotAssigned.java
NotAssigned.java:10: error: variable advice might not have been initialized
System.out.println(advice);
^
1 errorTo 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:
String advice;
if (temperature < 5) {
advice = "Take a coat.";
} else {
advice = "No coat needed.";
}
System.out.println(advice);> 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.
| Operator | Name | True when |
|---|---|---|
a && b | and | both a and b are true |
a || b | or | at least one of a and b is true (both is fine) |
!a | not | a 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.
a | b | a && b | a || b |
|---|---|---|---|
| true | true | true | true |
| true | false | false | true |
| false | true | false | true |
| false | false | false | false |
a | !a |
|---|---|
| true | false |
| false | true |
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 +.
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);> 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.
int age = 20;
boolean hasTicket = false;
boolean isMember = true;
boolean canEnter = age >= 18 && (hasTicket || isMember);
System.out.println("Can enter: " + canEnter);> 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:
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.");
}
}
}> 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 &&:
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.");
}
}
}> 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.
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);> 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:
!- arithmetic:
* / %, then+ - - comparisons:
< > <= >=, then== != &&||- the conditional operator
? :, met later in this lesson - 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 ||.
What do the first three lines print? (The fourth is the age + 1 >= 18 && age < 65 example above, with age equal to 17.)
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
> 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:
!(a && b)is the same as!a || !b!(a || b)is the same as!a && !b
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.
a | b | a && b | !(a && b) | !a | !b | !a || !b |
|---|---|---|---|---|---|---|
| true | true | true | false | false | false | false |
| true | false | false | true | false | true | true |
| false | true | false | true | true | false | true |
| false | false | false | true | true | true | true |
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.
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));> 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:
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");
}
}
}> javac ChainedRange.java
ChainedRange.java:4: error: bad operand types for binary operator '<='
if (0 <= x <= 10) {
^
first type: boolean
second type: int
1 errorThe 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 ||:
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");
}> 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
With temperature equal to 20, the coat message should not appear. Look closely at line 4. What does this program print?
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
> 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.
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.");> 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:
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);> 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:
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"));> 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:
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"));> 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 : valueIfFalseIt 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 :.
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") + ".");> 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:
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);
}
}> 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.
public class TernaryTypes {
public static void main(String[] args) {
boolean found = true;
int result = found ? 1 : "none";
System.out.println(result);
}
}> 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 errorHere 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
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.");> 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:
int sides = 7;
switch (sides) {
case 3:
System.out.println("triangle");
break;
case 4:
System.out.println("quadrilateral");
break;
}
System.out.println("Done.");> 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.
Here sides is 4, and the break after the "quadrilateral" line has been forgotten. What is printed?
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
> 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:
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");
}> 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:
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);
}> javac CommandSwitch.java > java CommandSwitch Halting.
You cannot switch on a double. The same is true of long and boolean; if handles those.
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");
}
}
}> 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 errorThe 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:
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");
}
}
}> javac CaseVariable.java
CaseVariable.java:6: error: constant expression required
case target:
^
1 errorMaking 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:
final int TARGET = 3;
int sides = 3;
switch (sides) {
case TARGET:
System.out.println("hit");
break;
default:
System.out.println("miss");
}> 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.
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.");> 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.
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);> 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:
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);
}
}> 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 errorThe 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:
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");
}
}
}> javac DupCase.java
DupCase.java:6: error: duplicate case label
case 5, 6, 7 -> System.out.println("Weekend");
^
1 errorDay 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.
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);
}> 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 when | Use an if chain when |
|---|---|
| you compare one value with a list of exact constants | the 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 codes | there 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.
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.
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.
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.
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.
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 nestedifs. - Then use a single
if/elseonleapto print one sentence:2100 is a leap yearwhenleapis true and2100 is not a leap yearwhen it is false (with your own value ofyearin place of 2100). The sample run below is for 2100.
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.
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:
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.
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: anif/else if/elsechain with comparison operators and logical operators. Noswitch.SeasonSwitch.java: an arrow-form switch expression assigned to aString, with several labels in onecase. Noif.
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.
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 invalidwith one expression built from||that is true when the sides do not make a triangle. - Declare
boolean validwith 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) andForms agree:followed by the result ofvalid == !invalid, which should betruefor any sides you try. - Then, if the triangle is valid, print
Valid: yesand a lineKind:followed byequilateral(all three sides equal),isosceles(exactly two equal) orscalene(none equal). If it is not valid, print onlyValid: noafter those first two lines.
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
- A comparison (
== != < > <= >=) produces aboolean.=assigns and==compares;if (x = 5)with anintis a compile-time error, but with abooleanit silently overwrites the variable. - An
ifruns its block when the condition is true;elseruns when it is false. In anelse ifchain the first true test wins, so order the tests from the most demanding to the least. Separateifs are independent; a chain picks one. - A variable lives from its declaration to the closing brace of its block. If you need a variable after the
if, declare it before theif, and end a chain withelseif the variable must be assigned on every path. &&,||and!combine conditions.&&and||short-circuit, so a guard on the left protects the right.!goes first, then&&, then||; use parentheses when you mix them. De Morgan's laws flip&&and||and negate each part. A range needs two comparisons:0 <= x && x <= 10.- Silent bugs: a semicolon after the condition, missing braces, a missing
break, and==ondoublevalues. Compare strings with.equals(...). condition ? a : bpicks one of two values; use it only for small choices.- A classic
switchfalls through until abreak. The arrow form (Java 14 and later) does not, allowscase 6, 7 ->, and as an expression produces a value that must cover every case. Switch onint,charorStringwith constant labels, and use anifchain for ranges and mixed conditions.
Words introduced in this lesson
| Term | Meaning |
|---|---|
| Condition | An expression whose value is a boolean. |
| Comparison operator | One of == != < > <= >=; compares two values and produces a boolean. |
| Block | Statements between a pair of braces. |
| Chain | An if followed by one or more else if parts and optionally a final else; the first true test wins. |
| Scope | The 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 table | A 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 operator | condition ? a : b, an expression that has the value a or b. |
switch | Chooses between cases by comparing one value with constant labels. |
| Fall-through | In a classic switch, continuing into the next case's statements because there was no break. |
| Switch expression | A switch that produces a value; it must cover every possible input. |