Computer Fundamentals and Introduction to Programming · Lecture Notes

Chapter 7: Conditionals

So far, the Java programs we have written execute the same lines in the same order every time they run. Real programs behave differently depending on the situation. A score below 60 prints “Fail”; otherwise the program prints “Pass”. A division is skipped when the divisor is zero. A warning appears when the user enters month 13. This chapter describes the constructs that let a program look at a condition and choose one of several paths. We begin with sequential execution and the idea of a condition. Next come if, if-else, the else-if chain, and nested decisions. Logical operators, short-circuit evaluation, the conditional operator, and string comparison let us write decisions more compactly and more safely. The switch construct selects among the discrete values of a single expression. The examples in the last section combine all of these constructs in realistic problems. Every program was compiled and run with JDK 21; the outputs shown are the programs' actual outputs.

Learning outcomes

Flow
Distinguish sequence, selection, and repetition structures; show in which order and under which conditions the lines of a program run by using a trace table.
Conditions
Write conditions that produce boolean values with comparison and logical operators; use short-circuit evaluation, De Morgan's laws, and operator precedence correctly.
Decisions
Build if, if-else, else-if chains and nested decisions in the right order; explain the difference between independent ifs and a chain, the dangling else problem, and the role of braces.
switch
Use the switch expression and statement for the discrete values of a single expression; explain default, yield, break, and fall-through; choose between if-else and switch.

7.1Control flow

A program is a list of statements given to the computer. A statement is the smallest complete unit of a program that does one job: declaring a variable, assigning a value, printing a line. In Java every simple statement ends with a semicolon. The order in which the computer executes these statements is called control flow. The language constructs that determine the flow are collectively called control structures.

7.1.1The three basic flows

However large an algorithm is, it can be written with only three forms of flow. Figure 7.1 shows the three side by side.

SequenceSelectionRepetitionstatement 1statement 2statement 3condition?truefalsepath Apath Bonly one path runscondition?truebodyfalserepeats while true
Figure 7.1: The three basic flows. Left: in a sequence, statements run once each, in the order written. Middle: in a selection, only one of the two paths runs, depending on the value of the condition. Right: in a repetition, the body repeats as long as the condition stays true.
Definition 7.1

A sequence structure is a flow in which statements run exactly once each, in the order written. A selection structure is a flow in which one of several paths is chosen according to the value of a condition; it is also called a conditional structure. A repetition structure is a flow in which a block of code runs over and over for as long as a condition holds.

Each of these three structures has a single entry and a single exit, so they can be nested inside one another. A branch of a decision can contain a sequence of statements, and the body of a loop can contain a decision. This chapter treats selection in detail. A sequence is the building block of a decision, so we examine it first.

7.1.2Sequence

The following four lines compute the area of a triangle. The base is 8 units and the height is 5 units.

double base = 8;
double height = 5;
double area = base * height / 2;
System.out.println(area);

The lines run from top to bottom. The first line creates the variable base and stores 8 in it. Because the variable's type is double, the integer 8 is converted automatically to 8.0. A conversion from a smaller type to a larger type is called a widening conversion. The second line does the same for height. The third line uses the values of the previous two variables and computes the area. The fourth line prints the result.

1base8.02height5.03area = 8.0 * 5.0 / 2 = 20.0420.0screenarea cannot be computed until base and height have values
Figure 7.2: A sequence. Lines 1 and 2 give values to base and height. Line 3 uses these two values to compute the area as 20.0. Line 4 prints the result.

Figure 7.2 uses arrows to show the dependencies between lines. The third line needs the values produced by the first and second lines. Every statement can use the state left behind by the statements before it. That is the essence of a sequence.

7.1.3Tracing a sequence step by step

The most reliable way to execute a program by hand is a trace table. In a trace table, each row shows one step and each column shows one variable. A cell holds the variable's value when that step has finished. A variable that does not exist yet is shown as “—”.

Table 7.1: Trace table of the area computation. Each row shows the state after the corresponding statement has finished.
StepLine executedbaseheightareaScreen
1double base = 8;8.0——
2double height = 5;8.05.0—
3abase * height8.05.0— (intermediate result 40.0)
3b40.0 / 2 → area8.05.020.0
4System.out.println(area);8.05.020.020.0

The third line is examined in two steps. * and / have the same precedence and are evaluated from left to right. First 8.0 × 5.0 = 40.0 is found, then 40.0 / 2 = 20.0. Only when both steps are finished is a value written into the area box. In the middle of an expression, the intermediate result exists only inside the processor; it is not stored in any variable. When the program runs, it produces this output:

20.0

In a sequence, the position of a line determines the result. If the third line is moved to the very top, base and height do not exist yet at that point. Java catches this error at compile time, before the program runs:

public class OrderError {
    public static void main(String[] args) {
        double area = base * height / 2;
        double base = 8;
        double height = 5;
        System.out.println(area);
    }
}
OrderError.java:3: error: cannot find symbol
        double area = base * height / 2;
                      ^
  symbol:   variable base
  location: class OrderError
OrderError.java:3: error: cannot find symbol
        double area = base * height / 2;
                             ^
  symbol:   variable height
  location: class OrderError
2 errors

The message means “symbol not found”. On line 3 the compiler looks for a variable named base and cannot find it. The same message is given for height. Java does not allow a variable to be used before the line on which it is declared.

Common mistake

Reading the formula “area = base × height / 2” as a definition, as in mathematics. In Java, = is not a declaration of equality but an assignment: the expression on the right is evaluated at that moment and the result is written into the box on the left. Even if base changes after the assignment, area is not updated automatically. The assignment has to run again to produce a new area.

7.2Conditions and if

At the heart of a selection structure is a question: “Is the score 60 or more?”, “Is the number negative?”, “Is the divisor zero?” Which path the program takes depends on the answer. In Java, this question is written as a condition.

7.2.1Conditions: expressions that produce a boolean

Definition 7.2

A condition is an expression whose value is true or false. The Java type that holds these two values is called boolean. Only an expression that produces a boolean value may appear in the parentheses of an if statement.

Most conditions are built by comparing two values. Java's six comparison operators are listed in Table 7.2. Each takes two numbers and produces a boolean value.

Table 7.2: Comparison operators. In the Example column, x = 7.
OperatorMeaningExampleValueOpposite
==equalx == 5false!=
!=not equalx != 5true==
<less thanx < 7false>=
<=less than or equalx <= 7true>
>greater thanx > 5true<=
>=greater than or equalx >= 9false<

The last column of the table gives the opposite of each operator. The opposite of > is not < but <=, because “not greater than 7” means “7 or less”, and 7 itself belongs to that set. This detail is the source of a common mistake when negating conditions.

Equality is tested with two equal signs (==). A single equal sign (=) is an assignment. Confusing the two is one of the most common mistakes beginners make. Fortunately, Java catches this confusion at compile time:

public class AssignInCondition {
    public static void main(String[] args) {
        int x = 7;
        if (x = 5) {
            System.out.println("five");
        }
    }
}
AssignInCondition.java:4: error: incompatible types: int cannot be converted to boolean
        if (x = 5) {
              ^
1 error

x = 5 is an assignment. The value of an assignment is the number assigned, here 5, and its type is int. An if, however, expects a boolean. That is why the compiler reports “int cannot be converted to boolean”. In some languages, such as C, any nonzero number counts as “true” and this line would compile silently. In Java, numbers and booleans are separate types; this strictness eliminates a whole class of errors.

The mathematical notation 10 < x < 20 does not work in Java either. The expression is read from left to right: first 10 < num is evaluated and yields a boolean value. Then the program tries to compare that boolean value with 20. “Less than” is meaningless for a boolean:

public class ChainedComparison {
    public static void main(String[] args) {
        int num = 15;
        if (10 < num < 20) {
            System.out.println("between");
        }
    }
}
ChainedComparison.java:4: error: bad operand types for binary operator '<'
        if (10 < num < 20) {
                     ^
  first type:  boolean
  second type: int
1 error

The message says that the < operator has a boolean on one side and an int on the other. The correct form combines the two comparisons with a logical AND: num > 10 && num < 20. Logical operators are treated in detail in Table 7.9.

7.2.2The one-way if

The simplest decision does a job if the condition is true and does nothing if it is false. For example, to turn a negative number into a positive one, an operation is needed only when the number is negative:

if (num < 0) {
    num = -num;
}

When execution reaches the if line, the expression in the parentheses is evaluated first. If the result is true, the statements between the braces run. If the result is false, those statements are skipped and execution continues at the line after the closing brace. In both cases the program reaches the next line; the work in between is either done or not. This pattern is traced in detail in the absolute value example.

7.2.3The if-else statement

Many decisions have a separate job for each of two cases. If the score is 60 or more, the program must print “Pass”; otherwise it must print “Fail”. For this we add an else branch to the if.

Definition 7.3

An if-else statement consists of two branches. If the condition is true, the body of the if runs; if it is false, the body of the else runs. On every execution exactly one of the branches runs; never both, and never neither. A branch is each of the paths that can be followed after a decision.

if (score >= 60) {
    System.out.println("Pass");
} else {
    System.out.println("Fail");
}
truefalseread scorescore >= 60print "Pass"print "Fail"End
Figure 7.3: Flowchart of the if-else statement. After the score is read, the condition score >= 60 is asked. The true branch prints “Pass” and the false branch prints “Fail”. The two branches join again at End.

In Figure 7.3, two arrows leave the decision box. One is labeled true and the other false. For any given score, only one of the two can be followed. At the ends of the arrows the two paths merge again; the program continues from the same point after the decision.

The boundary value in the condition needs care. With score >= 60, 60 falls on the “Pass” side. If score > 60 had been written, a student with exactly 60 would fail. The most common error in a decision is putting the boundary on the wrong side. For this reason a decision is always tested with the boundary value and with its two neighbors (such as 59 and 61). Every possible value goes to exactly one branch: scores from 0 to 59 go to the else branch, and 60 and above go to the if branch.

7.2.4Tracing if-else step by step

The following program reads the score from the keyboard. The Scanner class is in the java.util package; to use it, the file begins with the line import java.util.Scanner;. From here on, to keep code fragments short, only the body of main is shown. The complete program is shown separately.

Scanner in = new Scanner(System.in);
int score = in.nextInt();
if (score >= 60) {
    System.out.println("Pass");
} else {
    System.out.println("Fail");
}

Let the program run three times, with the user entering 75, 60, and 45 in turn. Table 7.3 gives the steps of each run.

Table 7.3: Three runs of the Pass/Fail program. The line numbers are the lines of the code above.
InputLine 2: scoreLine 3: conditionBranch executedBranch skippedOutput
757575 >= 60 → trueline 4line 6Pass
606060 >= 60 → trueline 4line 6Pass
454545 >= 60 → falseline 6line 4Fail
truefalseread scorescore >= 60print "Pass"print "Fail"End truefalseread scorescore >= 60print "Pass"print "Fail"End
Figure 7.4: The path followed in two runs. (a) score = 75: the condition is true, the “Pass” box runs, and the “Fail” box stays faded. (b) score = 45: the condition is false and only the “Fail” box runs.

The second run tests the boundary value. 60 >= 60 is true because >= includes equality. Figure 7.4 uses color to show the path followed in two runs. In every run, one of the branches does not run at all. The complete program and the outputs obtained with the inputs 75, 60, and 45 are as follows:

import java.util.Scanner;

public class PassFail {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int score = in.nextInt();
        if (score >= 60) {
            System.out.println("Pass");
        } else {
            System.out.println("Fail");
        }
    }
}
Pass
Pass
Fail

7.2.5Blocks, braces, and the empty statement

A group of statements between braces is called a block. Java's rule is this: the body of an if and the body of an else is a single statement. A block counts as one statement, however many statements it contains. When the body is a single simple statement, the braces may be omitted:

if (score >= 60)
    System.out.println("Pass");
else
    System.out.println("Fail");

This form is short, but it has two traps. The first appears when a second line is added to the body. The indentation suggests that the added line also belongs to the if, but the compiler does not look at indentation. Without braces, the if controls only the single statement that immediately follows it; the second line runs in every case.

public class NoBraces {
    public static void main(String[] args) {
        int x = 2;
        if (x > 5)
            System.out.println("A");
            System.out.println("B");
        System.out.println("C");
    }
}
B
C

For x = 2, 2 > 5 is false. Only println("A") is skipped. Although the “B” line is indented, it is outside the if and it runs. If the programmer meant to control both A and B, the two lines must be enclosed in braces.

The second trap is a semicolon accidentally placed at the end of the if line. A lone semicolon is also a statement in Java: the empty statement, which does nothing. When you write if (x > 0);, the body of the if becomes this empty statement. The line below is no longer controlled by the condition.

public class EmptyStatement {
    public static void main(String[] args) {
        int x = -3;
        if (x > 0);
            System.out.println("Positive");
        System.out.println("Done");
    }
}
Positive
Done

Although x = −3, “Positive” is printed. −3 > 0 is false and the empty statement is skipped, but there is nothing else to skip. The compiler does not count this line as an error because nothing breaks the rules. The mistake shows up only in the program's output.

Common mistake

Adding a second line to the body of a one-line if later and forgetting the braces. Because the indentation looks right, the error goes unnoticed. For this reason many coding guidelines require braces even when the body is a single line. Braces also make the if (...); mistake visible: a line such as if (x > 0); { stands out when read.

7.3Multiway decisions

Decisions with two options are built with if-else. What happens when there are more than two options? Converting a score to a letter grade needs four options: 90 and above is A, 80–89 is B, 70–79 is C, and below 70 is F. A decision of this kind is called a multiway decision.

7.3.1The else-if chain

Definition 7.4

An else-if chain is a multiway decision built by putting a new if in the body of each else. The conditions are tried in order from top to bottom. The branch of the first condition that is true runs; the rest of the chain is skipped without being checked. If no condition holds, the final else, if there is one, runs.

if (score >= 90) {
    grade = 'A';
} else if (score >= 80) {
    grade = 'B';
} else if (score >= 70) {
    grade = 'C';
} else {
    grade = 'F';
}

Seeing that the chain actually consists of nested if-else statements makes the rule easier to understand. The body of the first else is the second if; the body of its else is the third if. Because the code would shift a little further right at every level, Java programmers write else if on the same line and keep all the branches aligned. As far as the language is concerned, there is no separate keyword else if; it is only a writing habit.

truefalsetruefalsetruefalsescore >= 90grade = 'A'score >= 80grade = 'B'score >= 70grade = 'C'grade = 'F'print grade
Figure 7.5: Flowchart of the else-if chain. The thresholds 90, 80, and 70 are tested in order from left to right. When a condition is true, that branch's assignment is made and execution goes directly to the “print grade” box. If all three conditions are false, grade = 'F'.

Figure 7.5 shows the shape of the chain. The false arrow of each decision box leads to the next decision. The true arrows go down to the assignment boxes. All paths finally merge at the “print grade” box. In one run, at most one assignment box runs.

7.3.2Tracing the chain step by step

Here is the short form of the letter-grade program. Because the branches are single statements, no braces are used; the conditions and assignments are aligned to keep the code readable.

int score = in.nextInt();
char grade;
if (score >= 90)      grade = 'A';
else if (score >= 80) grade = 'B';
else if (score >= 70) grade = 'C';
else                grade = 'F';
System.out.println(grade);

The char grade; on the second line declares the variable but gives it no value. One of the branches of the chain assigns the value. Let the program run for 75, 95, and 50.

Table 7.4: Three runs of the else-if chain. “skipped” means the condition is never evaluated.
scorescore >= 90score >= 80score >= 70Branch executedCondition testedOutput
75falsefalsetruegrade = 'C'3C
95trueskippedskippedgrade = 'A'1A
50falsefalsefalsegrade = 'F' (else)3F

For 75, the first two conditions are false: 75 >= 90 and 75 >= 80. The third condition, 75 >= 70, is true, so grade = 'C' is executed. Even if no further conditions remained in the chain, the rule would be the same: after the chosen branch, execution jumps directly to the end of the chain. For 95, the first condition is true; the other two conditions are never evaluated. For 50, all three conditions are false and the else runs.

truefalsetruefalsetruefalsescore >= 90grade = 'A'score >= 80grade = 'B'score >= 70grade = 'C'grade = 'F'print grade truefalsetruefalsetruefalsescore >= 90grade = 'A'score >= 80grade = 'B'score >= 70grade = 'C'grade = 'F'print grade
Figure 7.6: The path followed in the chain. (a) score = 75: after two false arrows, the third condition is true and the grade = 'C' box runs. (b) score = 50: all three conditions are false; the path reaches the rightmost grade = 'F' box.

The boundaries of the chain should be tested too. The program was also run for 90, 89, 80, 70, and 69. It printed A, B, B, C, and F, respectively. A difference of a single unit between 90 and 89, or between 70 and 69, changes the grade; each threshold includes its own value.

7.3.3The order of thresholds

Each condition in the chain sets a lower bound on its own: “at least 80”, “at least 70”. No upper bound is written. The condition of the B branch does not have to be score >= 80 && score < 90, because execution reaches B's condition only if A's condition is false; at that point it is already known that the score is less than 90. In a chain, every condition automatically carries the knowledge that the previous conditions were false.

This convenience carries a responsibility: the thresholds must be written from largest to smallest. The following program shows what happens when the order is reversed.

import java.util.Scanner;

public class ReversedThresholds {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int score = in.nextInt();
        if (score >= 60) System.out.println("D");
        else if (score >= 70) System.out.println("C");
        else if (score >= 80) System.out.println("B");
        else if (score >= 90) System.out.println("A");
        else System.out.println("F");
    }
}
D

For 85, the first condition 85 >= 60 is true and D is printed. The rest of the chain is skipped. The program also prints D for 95. Every score of 60 and above gets a D. The C, B, and A branches cannot be reached with any input. Such code does not produce a compile error; the mistake shows up only when it is tested with an input whose correct output is known.

Common mistake

Arranging the thresholds from smallest to largest in a chain built on lower bounds. The general rule is: ask the narrower condition first. Every score that satisfies “at least 90” also satisfies “at least 70”. If the broader condition is asked first, the narrower one never gets its turn.

7.3.4Independent ifs versus an else-if chain

If the same three conditions are written one under another without the else keywords, a completely different program results. This form is called independent ifs: none of them is in the else branch of the previous one, and each is checked independently of the others.

int score = 95;
if (score >= 90) System.out.println("A");
if (score >= 80) System.out.println("B");
if (score >= 70) System.out.println("C");
A
B
C

For score = 95, all three conditions are true and three lines are printed. The first if printing A does not affect the second if; the second if is still tested. One expects a student to receive a single letter, but three letters appear. When the same conditions are linked with else if, only the first true branch runs:

int score = 95;
if (score >= 90) System.out.println("A");
else if (score >= 80) System.out.println("B");
else if (score >= 70) System.out.println("C");
A
Table 7.5: Comparison of the two forms for score = 95.
ConditionsIndependent ifselse-if chain
score >= 90tested: true → Atested: true → A
score >= 80tested: true → Bnot tested
score >= 70tested: true → Cnot tested
Output3 lines: A, B, C1 line: A

When the branches assign to a variable instead of printing, the error is more insidious. In Figure 7.7, every branch assigns a value to grade. In the independent form, a later assignment overwrites an earlier one. Because only a single letter is visible on the screen, the output “looks right”, but the grade is wrong.

independent ifsscore >= 90 → truegrade='A'score >= 80 → truegrade='B'result: grade = 'B'✗ wrongelse ifscore >= 90 → truegrade='A'score >= 80skippedresult: grade = 'A'✓ correct
Figure 7.7: Two forms for score = 95. Left, independent ifs: both conditions are true, the second assignment overwrites the first, and grade = 'B' remains. Right, else-if: when the first condition is true, the second is skipped and grade = 'A' remains.
public class IndependentGrade {
    public static void main(String[] args) {
        int score = 95;
        char grade = 'F';
        if (score >= 90) grade = 'A';
        if (score >= 80) grade = 'B';
        System.out.println(grade);
    }
}
B

Independent ifs are not always wrong. When each of several independent questions is to be asked separately, it is the right structure. For example, on an application form, separate warnings are written for “Is the name empty?”, “Is the e-mail invalid?”, and “Is the age under 18?” One being true should not prevent the others from being asked. The rule of choice is this: use else if when only one of the options can apply, and independent ifs when each can apply on its own.

7.3.5The final else and a variable that was never assigned

The else at the end of the chain catches the case in which no condition holds. This branch is not mandatory. But if it is deleted from the letter-grade program, the Java program does not compile:

public class UnassignedGrade {
    public static void main(String[] args) {
        int score = 75;
        char grade;
        if (score >= 90)      grade = 'A';
        else if (score >= 80) grade = 'B';
        else if (score >= 70) grade = 'C';
        System.out.println(grade);
    }
}
UnassignedGrade.java:8: error: variable grade might not have been initialized
        System.out.println(grade);
                           ^
1 error

The message means “the variable grade might not have been given a value”. The compiler examines all paths. When all three conditions are false, no value is assigned to grade. If execution reached the println(grade) line along that path, there would be no value to print. Java does not allow an unassigned local variable to be read. This rule prevents programs in which “it is unclear what the variable holds” already at compile time.

The problem can be solved in two ways: either the final else is put back, or the variable is given an initial value when it is declared (char grade = 'F';). The first way is clearer: the code shows one by one which letter each possible score goes to.

7.4Nested decisions

Some questions make sense only after the answer to another question is known. For permission to drive a vehicle, age is checked first. If the person is under 18, there is no point asking whether they have a license. If the age is sufficient, the second question is asked: do they have a license?

7.4.1A decision inside a branch

Definition 7.5

A nested decision is a selection structure placed inside one of the branches of another selection structure. The inner condition is checked only when the outer condition selects that branch.

int age = in.nextInt();
boolean license = in.nextBoolean();
if (age >= 18) {
  if (license)
    System.out.println("Can drive");
  else
    System.out.println("Get a license first");
} else {
  System.out.println("Too young");
}
truefalsetruefalseage >= 18licenseprint "Can drive"print "Get a license first"print "Too young"
Figure 7.8: A nested decision. First age >= 18 is asked. The true branch contains a second decision, license, which prints two different messages. The false branch prints “Too young” directly.

Figure 7.8 shows the structure. There is a second decision box in the true branch of the outer decision. This box is reached only when the age condition is satisfied. The program has three possible outputs, each at the end of a separate path.

In the code, nextBoolean() reads the word true or false from the keyboard and converts it to a boolean value. The form if (license) is also worth noting. license is already a boolean variable; there is no need to write if (license == true). The variable itself is the condition.

7.4.2Tracing a nested decision step by step

Let the program run with three input pairs: (20, true), (20, false), and (15, true).

Table 7.6: Three runs of the nested decision.
agelicenseOuter condition age >= 18Inner condition licenseOutput
20true20 >= 18 → truetrueCan drive
20false20 >= 18 → truefalseGet a license first
15true15 >= 18 → falsenot checkedToo young
truefalsetruefalseage >= 18licenseprint "Can drive"print "Get a license first"print "Too young" truefalsetruefalseage >= 18licenseprint "Can drive"print "Get a license first"print "Too young"
Figure 7.9: The path followed in a nested decision. (a) age = 20, license = true: both conditions are true and “Can drive” is printed. (b) age = 15: the outer condition is false; the inner decision box stays faded because it is never checked.

The third run shows what nesting means. The 15-year-old's license was entered as true; in real life this is impossible, but it does not matter to the program. When the outer condition is false, the inner if line is never reached. The actual outputs of the complete program:

import java.util.Scanner;

public class License {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int age = in.nextInt();
        boolean license = in.nextBoolean();
        if (age >= 18) {
          if (license)
            System.out.println("Can drive");
          else
            System.out.println("Get a license first");
        } else {
          System.out.println("Too young");
        }
    }
}
Can drive
Get a license first
Too young

7.4.3Using && instead of nesting

A nested structure shifts the code a little further right at every level. At a depth of three or four levels, it is hard to follow which else belongs to which if. In many cases, nested decisions can be turned into a flat chain by combining them with the logical AND (&&):

import java.util.Scanner;

public class LicenseAnd {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int age = in.nextInt();
        boolean license = in.nextBoolean();
        if (age >= 18 && license)
            System.out.println("Can drive");
        else if (age >= 18)
            System.out.println("Get a license first");
        else
            System.out.println("Too young");
    }
}

The first condition catches the case “18 or older and licensed”. The second condition is reached only if the first is false. At that point, if age >= 18 is true, the person has no license. Every remaining case is insufficient age. For four input pairs, the program gave the same output as the nested version:

Table 7.7: Outputs of the nested version and the && version for four inputs.
InputLicense (nested)LicenseAnd (&&)
20 trueCan driveCan drive
20 falseGet a license firstGet a license first
15 trueToo youngToo young
15 falseToo youngToo young

Which form to choose depends on readability. If the second question really depends on the first, that is, if the second question is meaningless when the first condition is false, the nested structure shows this dependency clearly. If the conditions carry equal weight, combining them on a single line with && is shorter and flatter.

7.4.4The dangling else

When braces are not used in nested ifs, an ambiguity arises. In the following code there is a single else but two ifs. Which one does the else belong to?

int a = -1, b = 5, x = 0;
if (a > 0)
    if (b > 0)
        x = 1;
    else
        x = 2;
System.out.println(x);
Definition 7.6

The dangling else is the situation in nested ifs without braces in which the notation does not make clear which if an else is attached to. Java's rule is definite: an else is attached to the nearest preceding if that does not yet have an else. Indentation does not change this rule.

In the code, the else is written aligned with the inner if; here the indentation agrees with the rule. Even so, a programmer might take the else to belong to the outer if. Let the initial values be a = −1, b = 5, x = 0. The steps are as follows:

  1. a > 0 is evaluated: −1 > 0 is false.
  2. The body of the outer if is skipped. This body is a single statement consisting of the inner if and its else. Therefore the else is skipped as well.
  3. x never changes; 0 is printed.
0

A programmer who believes the else belongs to the outer if expects 2. In reality the else is attached to the inner if, and since the inner if is never reached, it does not run either. The rule becomes even clearer when the same code is tried with different inputs:

Table 7.8: Running the dangling else code with four inputs. The program has been modified to read the initial values of a, b, and x from the keyboard.
abx (initially)a > 0b > 0Assignment executedOutput
−150falsenot checkednone0
−469falsenot checkednone9
350truetruex = 11
3−20truefalsex = 2 (inner else)2

The assignment x = 2 runs only when a is positive and b is not. This is proof that the else belongs to the inner if. The result does not change even if the else line is moved all the way to the left, aligned with the outer if. The compiler does not read whitespace.

If the programmer's intention is to attach the else to the outer if, the inner if is closed with braces. The closing brace ends the inner if; the else that follows can no longer attach to it.

int a = -1, b = 5, x = 0;
if (a > 0) {
    if (b > 0) x = 1;
} else {
    x = 2;
}
System.out.println(x);
2

With the same initial values, −1 > 0 is false. This time the else belongs to the outer if and it runs: x = 2, and 2 is printed. The only difference between the two programs is a pair of braces; the outputs are 0 and 2.

Common mistake

Working out what the code does by looking at the indentation. Indentation is meant only for the reader; to the Java compiler, spaces and line breaks are meaningless. Writing every body with braces in nested ifs removes the ambiguity entirely. The “format code” command of development environments also rearranges the indentation to match the structure the compiler sees; a dangling else moves to its real place after formatting.

7.5Decisions with logical operators

Real decisions often depend on more than one condition. An application is accepted if the person is 18 or older and has a document. A day is part of the weekend if it is Saturday or Sunday. The Java counterparts of the connectives “and”, “or”, and “not” are the logical operators.

7.5.1&&, || and !

Definition 7.7

Logical operators combine boolean values and produce a new boolean value. a && b (AND) is true only when both sides are true. a || b (OR) is true when at least one side is true. !a (NOT) reverses the value.

Table 7.9: Truth table of the logical operators. The four rows are all combinations of two boolean values.
aba && ba || b!a
falsefalsefalsefalsetrue
falsetruefalsetruetrue
truefalsefalsetruefalse
truetruetruetruefalse

The meaning of || differs from the “either … or …” of everyday language. In everyday speech, “either tea or coffee” often means exactly one of the two. ||, however, also gives true when both sides are true. The application example is written with && as follows:

boolean eligible = age >= 18 && hasDoc;
if (eligible) {
    System.out.println("Application accepted");
}
age >= 18hasDoc&&eligibleboth must be truehasDoctruefalseage >= 18 ↓truefalsetruefalsefalsefalsevalue of eligible
Figure 7.10: The values of age >= 18 and hasDoc combine through && to form eligible. In the table on the right, of the four combinations only the cell where both are true gives true.

The result of the condition is first assigned to a boolean variable named eligible. This is not required; the condition could also have been written directly in the parentheses of the if. But giving the condition a name makes the code readable: the line if (eligible) explains itself.

7.5.2Short-circuit evaluation

&& and || evaluate the left side first. If the left side alone determines the result, the right side is not evaluated at all.

Definition 7.8

Short-circuit evaluation: in the expression a && b, if a is false, the result is false whatever b is, and b is not evaluated. In a || b, if a is true, the result is true and b is not evaluated. The right side is evaluated only when it is needed to determine the result.

Let us trace the application program for three inputs:

int age = in.nextInt();
boolean hasDoc = in.nextBoolean();
boolean eligible = age >= 18 && hasDoc;
if (eligible) {
    System.out.println("Application accepted");
}
Table 7.10: Evaluation of the expression eligible = age >= 18 && hasDoc for three inputs.
agehasDocLeft: age >= 18Right: hasDoceligibleOutput
20truetrueread: truetrueApplication accepted
20falsetrueread: falsefalse(no output)
16truefalsenot readfalse(no output)

In the third row the left side is false. Whatever the value of the right side, the result of the AND will be false; Java never looks at hasDoc. In this example, short-circuiting is only a small time saving. Its real importance appears where the right side can be evaluated safely only when the left side is true. A divisor that must not be zero in a division is such a condition:

if (b != 0 && a / b > 1) { … }

If b = 0, the left side is false and a / b is never evaluated. Division by zero with integers is an error that stops the program. Short-circuiting places the right side of the condition under the protection of the left side. Order matters: had a / b > 1 && b != 0 been written, the division would be performed before the check.

7.5.3De Morgan's laws

If we need to write the case in which the application is rejected, the most direct way is to put ! in front of the acceptance condition: !(age >= 18 && hasDoc). This form is correct but hard to read. The reader must first think about the inside of the parentheses and then about its opposite. De Morgan's laws let us distribute ! into the parentheses and obtain a flatter condition.

Theorem 7.1 (De Morgan's laws)

For all boolean values a and b,

!(a && b) == (!a || !b) and !(a || b) == (!a && !b)

hold. When ! is distributed into the parentheses, && and || swap places and each term is negated.

The proof is by truth table. There are only four combinations of values that a and b can take; if both sides give the same value in all four, the equality holds in every case. Table 7.11 gives the four rows. The table was produced by a Java program that computed the four combinations one by one.

Table 7.11: Truth table of De Morgan's laws. The third and fourth columns are the same in every row; so are the fifth and sixth columns.
ab!(a && b)!a || !b!(a || b)!a && !b
falsefalsetruetruetruetrue
falsetruetruetruefalsefalse
truefalsetruetruefalsefalse
truetruefalsefalsefalsefalse

When the rule is applied to the rejection condition, the term !(age >= 18) simplifies as well. “Not greater than or equal to 18” means “less than 18”. The rejection condition therefore takes this form:

// Reject: under 18 or no document
if (!(age >= 18 && hasDoc)) { … }
// Same condition by De Morgan:
if (age < 18 || !hasDoc) { … }

The equivalence of the two conditions was also tested with a program: age from 0 to 40 and both values of hasDoc, 41 × 2 = 82 combinations in all. In all 82 combinations the two conditions gave the same result. The opposites of the comparisons are in the last column of Table 7.2: >= ↔ <, > ↔ <=, == ↔ !=.

Example 7.1

How can the case in which a temperature is not between 15 and 30 (both bounds included) be written without using !?

Solution. The inside of the range is t >= 15 && t <= 30. The outside is its opposite: !(t >= 15 && t <= 30). By De Morgan's law, && turns into || and each term is negated: !(t >= 15) → t < 15, !(t <= 30) → t > 30. The result is t < 15 || t > 30. A temperature cannot be below 15 and above 30 at the same time, so if && had been kept in the condition, no value would satisfy it.

7.5.4The non-short-circuit & and |

In Java the single-character operators & and | can also be used with boolean values. Their logical results are the same as those of && and ||. The difference lies in the way of evaluation: the single-character operators always evaluate both sides. This difference becomes visible when the right side contains an error or a side effect.

public class ShortCircuit {
    public static void main(String[] args) {
        int a = 10, b = 0;
        if (b != 0 && a / b > 1) {
            System.out.println("big");
        }
        System.out.println("&& is safe");
        if (b != 0 &  a / b > 1) {
            System.out.println("big");
        }
        System.out.println("never reached");
    }
}
&& is safe
Exception in thread "main" java.lang.ArithmeticException: / by zero
	at ShortCircuit.main(ShortCircuit.java:8)

The line with && passes safely and “&& is safe” is printed. In the line with &, however, a / b is evaluated even though b = 0. Java throws an exception: ArithmeticException: / by zero. The program stops at line 8, and the last println is never reached.

One way to see the side effect is to write a small method that increments a counter every time it is called:

static int count = 0;
static boolean check(boolean v) { count++; return v; }
Table 7.12: Before each expression, count is set to 0. While the logical result stays the same, the counter shows how many sides were evaluated.
ExpressionResultcountExplanation
check(false) && check(true)false1Left is false; right is not called.
check(false) & check(true)false2Both sides are called.
check(true) || check(true)true1Left is true; right is not called.
check(true) | check(true)true2Both sides are called.

The values in the table are the output of the program below. In each line, the result is printed first and then the counter.

public class Counter {
    static int count = 0;
    static boolean check(boolean v) { count++; return v; }

    public static void main(String[] args) {
        boolean r;
        count = 0; r = check(false) && check(true); System.out.println(r + " " + count);
        count = 0; r = check(false) &  check(true); System.out.println(r + " " + count);
        count = 0; r = check(true)  || check(true); System.out.println(r + " " + count);
        count = 0; r = check(true)  |  check(true); System.out.println(r + " " + count);
    }
}
false 1
false 2
true 1
true 2

Conditions almost always use && and ||. The real use of & and | is bit operations on integers.

Common mistake

Putting an operation that changes a variable (such as ++k) inside a condition. Because of short-circuiting, whether this operation runs depends on the value of the left side. In the line if (k > 0 && ++k > 5), k is incremented only when it is positive. The behavior of such code is hard to follow; the increment should be done on a separate line before the condition.

7.5.5Operator precedence

A condition can contain arithmetic, comparison, and logical operators together. Operator precedence determines which is evaluated first. The precedence of the operators that occur often in conditions is given in Table 7.13, from highest to lowest.

Table 7.13: Precedence of operators that occur often in conditions (the upper one is evaluated first).
RankOperatorsKind
1!, unary -, ++, --unary
2* / %multiplicative
3+ -additive
4< <= > >=relational
5== !=equality
6&non-short-circuit AND
7|non-short-circuit OR
8&&AND
9||OR
10? :conditional operator
11= += …assignment

Thanks to this ordering, year % 4 == 0 && year % 100 != 0 can be written without parentheses. First the % operations are evaluated, then the == and != comparisons, and && last. It is also important that && comes before ||: the expression a || b && c is read as a || (b && c). The precedence of ! is the highest, so parentheses are needed when negating a comparison: !(x > 5). Without parentheses, !x > 5 means (!x) > 5 and does not compile if x is a number. Whenever you are unsure about precedence, using parentheses both prevents errors and helps the reader.

7.6The conditional operator ?:

When the only job of a decision is to give a variable one of two values, if-else takes four lines:

int max;
if (a > b) max = a;
else       max = b;

Java offers a shorter notation for this pattern.

Definition 7.9

The conditional operator (also called the ternary operator because it takes three operands) is written as condition ? value1 : value2. If the condition is true, the value of the expression is value1; if it is false, the value is value2. Only the selected value is evaluated.

An if-else is a statement: it does something but does not produce a value. The conditional operator, however, is an expression: it produces a value. It can therefore be used on the right side of an assignment, in the argument of a method, or inside another expression.

int a = 7, b = 12;
int max = (a > b) ? a : b;
System.out.println(max);
a7intb12intmax12inta > bfalse?anot examined:btrue→ 12
Figure 7.11: Evaluation of the expression (a > b) ? a : b for a = 7, b = 12. Because the condition is false, the b after the colon is chosen; a is not examined. max = 12.

The steps are as follows. First the condition is evaluated: 7 > 12 is false. Because the condition is false, the value after the colon (:), that is, b, is chosen. The value of the expression is 12 and it is assigned to max. The program prints 12:

12

The conditional operator can also be nested. An expression that finds the sign of a number as “+”, “-”, or “0” looks like this:

String sign = n > 0 ? "+" : n < 0 ? "-" : "0";

The conditional operator groups from the right. The expression is read as n > 0 ? "+" : (n < 0 ? "-" : "0"). For n = −5, the first condition is false; the part in parentheses is evaluated, and since −5 < 0 is true, “-” is chosen. This is a short and correct expression, but three or four levels of nested conditional operators become unreadable. The conditional operator is most useful for short selections between two values. When the options multiply, an else-if chain or a switch is clearer.

The two values of a conditional operator must have compatible types. int m = a < b ? a : "none"; does not compile, because one branch of the expression is an int and the other is a string, and the result cannot be put into an int variable.

7.7Comparing strings: == and equals

Numbers are compared with ==. Strings (String) are different, and this is one of the points where Java beginners most often get stuck. A string variable stores not the text itself but the location of the object that holds the text in memory, that is, a reference. == compares two references: do the two variables point to the same object? The equals method is used to compare content.

String s1 = "java";
String s2 = "java";
String s3 = new String("java");
System.out.println(s1 == s2);
System.out.println(s1 == s3);
System.out.println(s1.equals(s3));
true
false
true
variablesstring poolheap (via new)s1"java"s2s3"java"
Figure 7.12: s1 and s2 point to the same "java" object in the string pool. s3 points to a separate "java" object created on the heap with new. The two objects have the same content but different locations.

Figure 7.12 shows the state of the three variables in memory. A piece of text written in quotation marks in code is called a string literal. Java keeps string literals in a shared region called the string pool. When the same literal is written a second time, no new object is created; the object in the pool is shared. That is why s1 and s2 point to the same object. new String("java"), however, always creates a new object. This object is in the heap, the region where objects created with new are kept.

Table 7.14: Explanation of the three comparisons.
ExpressionWhat does it compare?ResultWhy?
s1 == s2referencetrueBoth point to the same object in the pool.
s1 == s3referencefalses3 points to the separate object on the heap.
s1.equals(s3)contenttrueThe two objects have the same characters: j, a, v, a.

The first line giving true is dangerous, because it gives the impression that == compares content. This result is only a by-product of the pool. A string read from the user does not enter the pool; Scanner creates it as a new object. The following program shows this:

import java.util.Scanner;

public class StringInput {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String answer = in.next();
        System.out.println(answer == "yes");
        System.out.println(answer.equals("yes"));
        System.out.println(answer.equalsIgnoreCase("YES"));
    }
}

When the user types “yes”, the output is:

false
true
true

Even though the user typed exactly “yes”, answer == "yes" is false: one is a new object read from the keyboard, the other is the constant in the pool. equals gives the correct result. When the user types “Yes”, however, equals also gives false, because it is case-sensitive: “Y” and “y” are different characters. A comparison that ignores letter case is done with equalsIgnoreCase:

false
false
true
Common mistake

Comparing strings with ==. In small experiments with literals the program seems to work correctly; with strings read from the user or concatenated inside the program, the result comes out wrong. The rule is simple: always compare strings with equals. If the string variable can be null, put the literal first: "yes".equals(answer). This form does not throw an error when answer is null; it simply returns false.

7.8switch

An else-if chain can build any multiway decision. In some decisions, however, all the conditions test the same variable in the same way: month == 1, month == 2, … month == 12. Grouping the twelve months into seasons would need a long || chain. The switch construct makes decisions of this kind shorter and more readable.

7.8.1When to use switch

switch (month)case 12, 1, 2→ "Winter"case 3, 4, 5→ "Spring"case 6, 7, 8→ "Summer"case 9, 10, 11→ "Autumn"default→ "Invalid"
Figure 7.13: A switch expression goes directly to the matching case according to the value of month. Each case lists one or several constant values; if none matches, default is chosen.

switch compares the value of a single expression with a series of constants and goes to the matching option. In Figure 7.13, the month value is routed to one of five options. The options are written with case labels. Each label carries one or several constant values. If no label matches, default is chosen.

In an else-if chain, the conditions are tried in order. In a switch, the program goes directly to the case that matches the value; the labels in between are not “tried and passed”. A switch is therefore suitable for choices made among the discrete values of a single variable: a month number, a day number, a menu option, an operator sign. Range conditions (“if the score is greater than 85”) and complex conditions that depend on several variables are written with if-else.

The value in a case label must be a constant known at compile time: 4, 'A', "+". A variable cannot be a label:

public class VariableCase {
    public static void main(String[] args) {
        int month = 4, limit = 4;
        switch (month) {
            case limit -> System.out.println("equal");
            default -> System.out.println("different");
        }
    }
}
VariableCase.java:5: error: constant expression required
            case limit -> System.out.println("equal");
                 ^
1 error

The expression that a switch tests can be of types such as int, char, and String. double and boolean values cannot be tested with a switch; use if-else for them.

7.8.2The switch expression

In the newer notation introduced in Java 14, each case is written with an arrow (->) and a switch can produce a value.

Definition 7.10

A switch expression is a switch that produces the value of the selected case as its result: x = switch (…) { … };. A switch statement, on the other hand, does not produce a value; it only runs the code of the selected case. A case written with an arrow is said to use the arrow form; in the arrow form, only the selected case runs.

String season = switch (month) {
    case 12, 1, 2 -> "Winter";
    case 3, 4, 5 -> "Spring";
    case 6, 7, 8 -> "Summer";
    case 9, 10, 11 -> "Autumn";
    default -> "Invalid";
};
123456789101112WinterSpringSummerAutumnmonth1..12a value like 13 → default: "Invalid"
Figure 7.14: The season wheel. 12, 1, and 2 are Winter; 3, 4, and 5 are Spring; 6, 7, and 8 are Summer; 9, 10, and 11 are Autumn. Values outside 1–12 go to default, “Invalid”.

Each line in the code is a case. The line case 12, 1, 2 -> "Winter"; means “if month is 12, 1, or 2, the value is "Winter"”. A case can list several values separated by commas. In this way the twelve months are covered in five lines (Figure 7.14). The switch expression as a whole is a value; this value is assigned to the variable season. Because this is an assignment statement, a semicolon follows the closing brace: };.

A switch expression must produce a result for every possible value. An int can take more than 4 billion values; the cases list only twelve of them. That is why default is mandatory. If it is deleted, the Java program does not compile:

NoDefault.java:4: error: the switch expression does not cover all possible input values
        String season = switch (month) {
                        ^
1 error

The message means “the switch expression does not cover all possible input values”. In a switch statement, however, default is optional; if no case matches, the switch ends without doing anything. The compiler also reports an error if the same value appears in two cases, because it would be unclear which branch the value goes to:

DuplicateCase.java:6: error: duplicate case label
            case 2, 3, 4, 5 -> "Spring";
            ^
1 error

7.8.3Tracing a switch expression step by step

int month = in.nextInt();
String season = switch (month) {
    case 12, 1, 2 -> "Winter";
    case 3, 4, 5 -> "Spring";
    case 6, 7, 8 -> "Summer";
    case 9, 10, 11 -> "Autumn";
    default -> "Invalid";
};
System.out.println(season);
Table 7.15: Three runs of the season program.
monthMatching caseValue of the switchseasonOutput
4case 3, 4, 5"Spring""Spring"Spring
12case 12, 1, 2"Winter""Winter"Winter
13none → default"Invalid""Invalid"Invalid

For month = 4, the program goes to the line case 3, 4, 5, where 4 is in the list. The value of this case is "Spring". It is assigned to season as the value of the switch expression and printed. The code of no other case runs. month = 13 is in no list; default is chosen. The program was also tried for 1, 7, 10, 0, and −3: it printed Winter, Summer, Autumn, Invalid, and Invalid.

Spring
Winter
Invalid

7.8.4A branch with a block, and yield

The right side of a case in the arrow form is a single expression. Sometimes a branch has to do other work before it produces the value: print a message, compute an intermediate value. Such a branch is put into a block with braces, and the value is given with the keyword yield.

Definition 7.11

yield is the statement that specifies, in a block branch of a switch expression, the value that the branch produces. When yield runs, the block ends and the given value becomes the value of the switch expression.

int year = 2024, month = 2;
int days = switch (month) {
    case 4, 6, 9, 11 -> 30;
    case 2 -> {
        System.out.println("February");
        yield year % 4 == 0 ? 29 : 28;
    }
    default -> 31;
};
System.out.println(days);
February
29

Because month = 2, the branch with the block is selected. The block first prints “February”. Then the yield line runs. The value here is computed with a conditional operator: since 2024 % 4 = 0, year % 4 == 0 is true and 29 is chosen. The value of the switch expression is 29; it is assigned to days and printed. The output is two lines: “February” and “29”.

The same program was also run with other inputs. For February of 2023, it printed “February” and 28 (2023 % 4 = 3). For April it printed only 30, and for January only 31; since the block was not selected in these two runs, the “February” line was not printed either. In this example the leap year rule is simplified: it checks only divisibility by 4. The program therefore also prints 29 for 1900, although 1900 is not a leap year. The full rule is given in the leap year example.

If a branch with a block ends without yield, the branch has no value. Java catches this at compile time:

public class NoYield {
    public static void main(String[] args) {
        int year = 2024, month = 2;
        int days = switch (month) {
            case 4, 6, 9, 11 -> 30;
            case 2 -> {
                System.out.println("February");
            }
            default -> 31;
        };
        System.out.println(days);
    }
}
NoYield.java:8: error: switch rule completes without providing a value
            }
            ^
  (switch rules in switch expressions must either provide a value or throw)
1 error

The message means “the switch rule completes without providing a value”; the extra line reminds us that rules in switch expressions must either provide a value or throw an exception.

7.8.5Classic switch, break, and fall-through

Before the arrow form, a switch in Java was written only with a colon (:). This classic notation is still valid today and is often seen in old code. In a classic switch, case labels are only entry points. The program enters at the matching label and runs all the code below until it sees break or reaches the end of the switch.

Definition 7.12

Fall-through is what happens in a classic switch when the code of a case finishes without a break: execution passes into the code of the next case. The label of the next case is not checked in the process. The break statement exits the switch.

int day = 2;
switch (day) {
  case 1: System.out.println("Mon"); break;
  case 2: System.out.println("Tue");
  case 3: System.out.println("Wed"); break;
  default: System.out.println("None");
}
Tue
Wed
case 1:"Mon"breakcase 2:"Tue"no break!case 3:"Wed"breakdefault:"None"no break!
Figure 7.15: The classic switch for day = 2. Execution enters case 2 directly and prints “Tue”. Because case 2 has no break, it falls through into the code of case 3 and prints “Wed”. The break in case 3 exits the switch; default does not run.

The steps are as follows. day = 2. The program goes directly to the label case 2:; case 1 is not checked. “Tue” is printed. There is no break on this line. Execution passes to the line below, the code of case 3:. That the label is 3 does not matter; a label is only an entry point. “Wed” is printed. The break on this line exits the switch and default does not run (Figure 7.15). The same program printed only “Mon” for day = 1, only “Wed” for 3, and “None” for 9.

Fall-through is sometimes used on purpose: so that several cases do the same job, the labels are written one under another and the code is put only under the last one. In the arrow form, this need is met by the comma-separated list. The following program separates weekdays from weekend days without needing fall-through:

import java.util.Scanner;

public class DayType {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int day = in.nextInt();
        switch (day) {
            case 1, 2, 3, 4, 5 -> System.out.println("Weekday");
            case 6, 7 -> System.out.println("Weekend");
            default -> System.out.println("Invalid day");
        }
    }
}
Weekday
Weekend
Invalid day

Fall-through never happens in the arrow form: the code of the selected case runs and the switch ends. There is no need to write break. Using the arrow form in new code prevents at the outset the error caused by a forgotten break.

Common mistake

Forgetting break in a classic switch. The program compiles and may even work correctly for most inputs; the error shows up only when the case missing its break is selected, through the extra lines it prints. Another misconception is to think that default always runs last. default can also be written in the middle of a switch, and the fall-through rule applies to it too: if it has no break, execution falls into the code of the case below it.

7.8.6if-else or switch?

if-else: range conditionsFailPassExcellent05085100score < 50   ·   score < 85   ·   elseeach branch covers a range of numbersswitch: discrete values1234567case 1, 2, 3, 4, 5"Weekday"case 6, 7"Weekend"constant values of a single variable
Figure 7.16: Left, number ranges with if-else: below 50 Fail, 50–85 Pass, 85 and above Excellent. Right, discrete values of a single variable with switch: 1–5 weekday, 6–7 weekend.

Figure 7.16 puts the natural areas of use of the two constructs side by side. Score ranges are continuous: between 50 and 85 there are infinitely many decimal values, and it is impossible to list them all as cases. Days, on the other hand, are discrete: there are only seven values and each can be listed by name. Table 7.16 compares the two constructs by several criteria.

Table 7.16: Comparison of if-else and switch.
Criterionif-elseswitch
Range conditionSuitableNot directly suitable
Many options by a single valueUsableUsually clearer
Complex logicSuitableLimited
Each branch produces a resultNeeds an assignmentA switch expression can return a value

The last row shows an important advantage. In an else-if chain, every branch assigns to the same variable separately, and it is easy to forget the assignment in one branch. In a switch expression, the value is assigned in a single place and the compiler checks that every possible value has a result.

7.9Examples

The examples in this section combine decision structures in realistic problems. Each example gives the problem and the idea of the solution first, then the code, then a trace for a few inputs and the program's actual output. In most examples the code itself is short; the real work is finding which inputs behave specially.

7.9.1Odd or even?

An integer is even if it is divisible by 2 with no remainder. In Java the remainder is found with the % operator. The remainder is the amount left over after a division: dividing 17 by 2 gives quotient 8 and remainder 1, because 17 = 2 × 8 + 1.

int num = in.nextInt();
if (num % 2 == 0)
    System.out.println("Even");
else
    System.out.println("Odd");

In the condition, % is evaluated first and then the result is compared with 0; % has higher precedence than ==. Let us trace the program for 17, −4, and −7.

Table 7.17: Three runs of the odd/even program.
numnum % 2num % 2 == 0Output
171falseOdd
−40trueEven
−7−1falseOdd
Odd
Even
Odd

The third row needs attention: the value of -7 % 2 is −1, not 1. In Java, integer division rounds toward zero: −7 / 2 = −3, not −4. The remainder is computed consistently with this quotient: −7 = 2 × (−3) + (−1). As a result, the sign of the remainder is always the same as the sign of the dividend. Figure 7.17 shows the remainders modulo 2 of the numbers from −4 to 4.

numnum % 2-40-3-1-20-1-100112031400 → Even1 or -1 → Odd (a negative odd number has remainder -1, so a test for == 1 fails)
Figure 7.17: The values of num % 2 for the numbers from −4 to 4. For even numbers the remainder is 0. For positive odd numbers the remainder is 1, and for negative odd numbers it is −1.

The values in the figure were also produced by a program. The second line prints the two conditions for −7, the quotient -7 / 2, and 7 % -2:

public class RemainderTable {
    public static void main(String[] args) {
        for (int num = -4; num <= 4; num++) {
            System.out.print(num % 2 + " ");
        }
        System.out.println();
        System.out.println((-7 % 2 == 1) + " " + (-7 % 2 != 0) + " " + (-7 / 2) + " " + (7 % -2));
    }
}
0 -1 0 -1 0 1 0 1 0 
false true -3 1

-7 % 2 == 1 is false and -7 % 2 != 0 is true. That 7 % -2 comes out as 1 also confirms the rule: even if the divisor is negative, the remainder takes the sign of the dividend, 7.

Common mistake

Testing for an odd number with the condition num % 2 == 1. This condition works for positive odd numbers but gives the wrong result for negative odd numbers: −7 is counted as “not odd”. Safe conditions compare the remainder with 0: num % 2 == 0 for even and num % 2 != 0 for odd. These two conditions are correct for every int.

7.9.2Absolute value and overflow

The absolute value of a number is its distance from zero: |−8| = 8, |5| = 5. If the number is negative its sign is changed; otherwise it is left as it is. This is the typical example of the one-way if: for non-negative numbers there is nothing to do.

int num = in.nextInt();
if (num < 0) {
    num = -num;
}
System.out.println(num);
-10-8-505810num < 0 → num = -num-8 (before)8 (after)0 and positives do not change
Figure 7.18: Absolute value on the number line. −8 is reflected about zero and becomes 8. 0 and positive values do not change.
Table 7.18: Three runs of the absolute value program. The third input is Integer.MIN_VALUE.
Inputnum < 0num = -numOutput
−8true−(−8) = 88
5falseskipped5
−2147483648true−(−2147483648) → overflow → −2147483648−2147483648
8
5
-2147483648

The first two rows give the expected result. The result in the third row, however, is surprising: the absolute value of a number has come out negative. The cause is the limits of the int type. An int is stored in 32 bits and can take values between −231 = −2,147,483,648 and 231 − 1 = 2,147,483,647. The positive counterpart of the smallest value, Integer.MIN_VALUE, is 2,147,483,648. This number is one more than the largest int and does not fit in an int.

Definition 7.13

Overflow is when the result of an operation falls outside the range of values that the type storing the result can hold. In Java, overflow in int and long operations does not cause an error; the result “wraps around” to the other end of the range. Adding 1 to the largest int gives the smallest int.

The correct result of −(−2,147,483,648) is 2,147,483,648. This value exceeds the largest int by 1 and wraps around to the other end of the range: the result is again −2,147,483,648. Java's built-in Math.abs method behaves the same way. There are two ways to handle this special case correctly. The first is to do the computation in a wider type, long. The second is to use the Math.absExact method, available since Java 15; instead of silently giving a wrong result, this method throws an exception.

public class AbsEdgeCase {
    public static void main(String[] args) {
        int num = Integer.MIN_VALUE;
        System.out.println(Integer.MAX_VALUE);
        System.out.println(Math.abs(num));
        long wide = num;
        if (wide < 0) wide = -wide;
        System.out.println(wide);
        System.out.println(Math.absExact(num));
    }
}
2147483647
-2147483648
2147483648
Exception in thread "main" java.lang.ArithmeticException: Overflow to represent absolute value of Integer.MIN_VALUE
	at java.base/java.lang.Math.absExact(Math.java:1903)
	at AbsEdgeCase.main(AbsEdgeCase.java:9)

The first line is the largest int. The second line shows that Math.abs also gives a negative result. In the third line the value has been copied into a long; the range of long is much wider and the correct result, 2147483648, is obtained. In the last line Math.absExact notices the overflow and throws an ArithmeticException. The message means that representing the absolute value of Integer.MIN_VALUE would overflow.

7.9.3Leap year

The Earth takes about 365.2425 days to complete one orbit around the Sun. The calendar balances this surplus with leap years, that is, years of 366 days. The rule of the Gregorian calendar has three steps:

  1. years divisible by 4 are leap years;
  2. but years divisible by 100 are not leap years;
  3. but years divisible by 400 are leap years again.

The rule can be collected into a single boolean expression: “divisible by 4 and not divisible by 100” or “divisible by 400”.

int year = in.nextInt();
boolean leap =
    (year % 4 == 0 && year % 100 != 0)
    || year % 400 == 0;
if (leap)
    System.out.println(year + " is a leap year");
else
    System.out.println(year + " is not a leap year");

The parentheses show that the part with && is a unit. Since && has higher precedence than ||, the result would not change without the parentheses, but the parentheses show the structure of the rule clearly to the reader. Let us trace the program for four years.

Table 7.19: Evaluation of the leap year condition for four years. “not examined” is a term that is not evaluated because of short-circuiting.
yearyear % 4 == 0year % 100 != 0Parenthesesyear % 400 == 0leap
20240 → true24 → truetruenot examinedtrue
20233 → falsenot examinedfalse23 → falsefalse
19000 → true0 → falsefalse300 → falsefalse
20000 → true0 → falsefalse0 → truetrue
year2024int(year % 4 == 0true&&year % 100 != 0true)||year % 400 == 0not examined→ true
Figure 7.19: Evaluation of the condition for year = 2024. Both terms inside the parentheses are true. Because the left side is true, || short-circuits; the term year % 400 == 0 is not examined.

In each row there are two chances for short-circuiting. In 2024 the inside of the parentheses is true and the right side of || is not examined (Figure 7.19). In 2023 the first term is false; && does not evaluate the second term. Because the inside of the parentheses is false, this time the right side of || is evaluated. 1900 and 2000 are the subtle points of the rule. Both are divisible by 100 and the inside of the parentheses comes out false. The difference is in the last term: 1900 % 400 = 300, 2000 % 400 = 0. That is why 2000 is a leap year and 1900 is not. The program printed “is not a leap year” for 2100 and “is a leap year” for 1600.

2024 is a leap year
2023 is not a leap year
1900 is not a leap year
2000 is a leap year

7.9.4The quadratic equation

The number of real roots of the equation ax² + bx + c = 0 depends on the discriminant: Δ = b² − 4ac. If Δ is positive there are two distinct real roots; if it is zero there is a single (repeated) root; if it is negative there are no real roots. The roots are found with this formula:

x1,2 = (−b ± √Δ) / (2a)

The three cases are separated by an else-if chain with three branches. Here a is assumed to be nonzero; if a = 0, the equation would not be quadratic.

double a = in.nextDouble();
double b = in.nextDouble();
double c = in.nextDouble();
double d = b * b - 4 * a * c;
if (d > 0) {
  double x1 = (-b + Math.sqrt(d)) / (2 * a);
  double x2 = (-b - Math.sqrt(d)) / (2 * a);
  System.out.println(x1 + " and " + x2);
} else if (d == 0) {
  System.out.println(-b / (2 * a));
} else {
  System.out.println("No real roots");
}
Table 7.20: Three runs of the equation program. A different branch runs in each row.
a, b, cd = b² − 4acBranch executedComputationOutput
1.0, −3.0, 2.09.0 − 8.0 = 1.0d > 0x1 = (3.0 + 1.0) / 2.0 = 2.0, x2 = (3.0 − 1.0) / 2.0 = 1.02.0 and 1.0
1.0, −2.0, 1.04.0 − 4.0 = 0.0d == 0−b / 2a = 2.0 / 2.0 = 1.01.0
1.0, 0.0, 1.00.0 − 4.0 = −4.0else—No real roots
2.01.01.0x² + (-3.0)x + 2.0two roots 1.01.0x² + (-2.0)x + 1.0one root 1.0x² + (0.0)x + 1.0no roots
Figure 7.20: The parabolas of the three runs. (a) Δ = 1.0: the parabola crosses the x-axis at 1.0 and 2.0. (b) Δ = 0.0: the parabola is tangent to the axis at 1.0. (c) Δ = −4.0: the parabola does not cross the axis.
2.0 and 1.0
1.0
No real roots

Figure 7.20 gives the geometric meaning of each run. The program was also tried for 2x² − 7x + 3 = 0: Δ = 49 − 24 = 25, √Δ = 5; the roots are (7 + 5) / 4 = 3.0 and (7 − 5) / 4 = 0.5. The program printed “3.0 and 0.5”.

The else branch does more than print a message; it also protects the program from an error. The square root of a negative number is undefined in the real numbers. In Java, Math.sqrt(-4.0) does not throw an exception; it returns NaN (Not a Number). Division by zero with floating-point numbers does not cause an error either; it produces infinity (Infinity):

public class FloatEdgeCases {
    public static void main(String[] args) {
        System.out.println(Math.sqrt(-4.0));
        System.out.println(7.0 / 0);
        System.out.println(-7.0 / 0);
        System.out.println(0.0 / 0);
        System.out.println(0.1 + 0.2 == 0.3);
        System.out.println(0.1 + 0.2);
    }
}
NaN
Infinity
-Infinity
NaN
false
0.30000000000000004

Every computation that involves NaN again gives NaN, and the error goes unnoticed until the results are printed on the screen. That is why the order of decisions matters: Math.sqrt(d) is called only in the branch where d > 0 is known.

The last two lines show another subtlety of floating-point numbers. 0.1 + 0.2 is not exactly 0.3; 0.1 and 0.2 cannot be represented exactly in binary, and a small rounding difference remains. The comparison d == 0 is safe in this example because the inputs are integers and b² − 4ac is computed exactly. For floating-point values that come from measurement, however, a small tolerance is used instead of ==: Math.abs(d) < 1e-9.

7.9.5The largest of three numbers

One way to find the largest of three numbers is to write every possibility as a separate condition: “if a is greater than b and than c …”. This approach gets complicated even with three numbers and becomes unmanageable with five. A better way is the “candidate and compare” pattern: the first number is taken as the candidate, then each number is compared with the candidate, and if it is larger than the candidate it becomes the candidate.

int a = in.nextInt();
int b = in.nextInt();
int c = in.nextInt();
int max = a;
if (b > max)
    max = b;
if (c > max)
    max = c;
System.out.println("Max: " + max);
Table 7.21: Three runs of the “candidate and compare” pattern. The last column is the candidate value after each step.
Input (a, b, c)StepConditionsmax
7, 12, 5max = a—7
b > max12 > 7 → true12
c > max5 > 12 → false12
3, 3, 9max = a—3
b > max3 > 3 → false3
c > max9 > 3 → true9
8, 2, 4max = a—8
b > max2 > 8 → false8
c > max4 > 8 → false8
7a12b5cmax12int
Figure 7.21: The state after the comparison with b for the input (7, 12, 5). The bars show the sizes of a, b, and c; the candidate has become max = 12.

In the second input, 3 > 3 is false; an equal value does not change the candidate. The result is still correct, because it does not matter which of the equal values is the candidate. The strength of the pattern is that it generalizes: for n numbers exactly n − 1 comparisons are needed, and each comparison has the same form. When this pattern is put in the body of a loop, it finds the largest of any number of numbers. The same job can also be done in one line with Java's built-in method: Math.max(a, Math.max(b, c)). The complete program prints the results of both methods:

import java.util.Scanner;

public class Largest {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int a = in.nextInt();
        int b = in.nextInt();
        int c = in.nextInt();
        int max = a;
        if (b > max)
            max = b;
        if (c > max)
            max = c;
        System.out.println("Max: " + max);
        System.out.println(Math.max(a, Math.max(b, c)));
    }
}
Max: 12
12
Max: -1
-1
Common mistake

Starting the candidate with 0 instead of the first number: int max = 0;. When the inputs are positive, this also gives the right result. But with the input (−2, −7, −1), no number is greater than 0; the candidate never changes and 0, which is not even one of the inputs, is printed. The correct program prints −1 for this input. The candidate is always initialized with one of the inputs.

7.9.6A calculator with switch

Let the user enter two numbers with an operator sign between them: 8.0 * 2.5. The program reads the sign as a string and chooses the corresponding operation with a switch. The next() method of Scanner reads the word up to the next whitespace as a string; that is why the input has spaces between the numbers and the sign.

double x = in.nextDouble();
String op = in.next();
double y = in.nextDouble();
switch (op) {
  case "+" -> System.out.println(x + y);
  case "-" -> System.out.println(x - y);
  case "*" -> System.out.println(x * y);
  case "/" -> {
    if (y == 0) System.out.println("Error!");
    else System.out.println(x / y);
  }
  default -> System.out.println("Invalid");
}
Table 7.22: Three runs of the calculator.
InputopMatching caseExtra conditionOutput
8.0 * 2.5"*"case "*"—20.0
7.0 / 0.0"/"case "/"y == 0 → trueError!
5.0 % 3.0"%"none → default—Invalid
8.0 * 2.5"+""-""*""/"default20.0
Figure 7.22: For the input 8.0 * 2.5, the switch goes to the case that carries op = "*" and prints 20.0.
20.0
Error!
Invalid

The division branch is not a single expression but a block containing an if-else. This is a switch statement and does not produce a value; therefore yield is not needed in the block. The check in the block is necessary, because division by zero with floating-point numbers does not cause an error: the expression 7.0 / 0 produces Infinity. To give the user a clear message instead of printing “Infinity”, the divisor is tested before the division. In the third run the “%” sign matches no case; default catches the unexpected input. A switch on a String matches with equals; the reference problem caused by using == on strings does not arise here.

The program was also tried for 9 - 4, 7 / 2, and 3 + 4.5; it printed 5.0, 3.5, and 7.5. Because x and y are double, 7 / 2 is not integer division and gives 3.5.

7.9.7Worked examples from the exercises

The following examples are selected from the exercises of the slides. Each applies a pattern described in this chapter.

Example 7.2

A program that prints whether the integer entered is positive, negative, or zero.

Solution. The three options are mutually exclusive; a number falls into only one of them. That is a job for an else-if chain. No condition is needed for the third case: if the number is neither positive nor negative, it is zero.

import java.util.Scanner;

public class SignCheck {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int num = in.nextInt();
        if (num > 0)
            System.out.println("Positive");
        else if (num < 0)
            System.out.println("Negative");
        else
            System.out.println("Zero");
    }
}

It prints “Positive” for 12, “Negative” for −3, and “Zero” for 0. 0 is a boundary value and was tested separately: 0 > 0 and 0 < 0 are false, so the else runs.

Example 7.3

A program that computes the body mass index from height (in meters) and weight in kilograms, BMI = weight / height², and prints its category. The limits: below 18.5 is underweight, from 18.5 to 25 is normal, and 25 and above is overweight.

Solution. The categories divide a continuous range; switch is not suitable. Because the thresholds are ordered from smallest to largest, the conditions are written with < and the chain starts from the smallest threshold.

import java.util.Scanner;

public class Bmi {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        double height = in.nextDouble();
        double weight = in.nextDouble();
        double bmi = weight / (height * height);
        if (bmi < 18.5)
            System.out.println("Underweight");
        else if (bmi < 25)
            System.out.println("Normal");
        else
            System.out.println("Overweight");
    }
}

For a height of 1.75 m and a weight of 70 kg, BMI = 70 / 3.0625 ≈ 22.86 and “Normal” is printed. For 1.60 m and 45 kg, 45 / 2.56 ≈ 17.58 and “Underweight” is printed; for 1.80 m and 90 kg, 90 / 3.24 ≈ 27.78 and “Overweight” is printed. The input to the program is given with a decimal point, as in Java source code: 1.75. If the computer's regional setting is Turkish, Scanner may expect a decimal comma; in that case type 1,75.

Example 7.4

Do three side lengths form a triangle? If so, is the triangle equilateral, isosceles, or scalene?

Solution. For three sides to form a triangle, the sum of any two sides must be greater than the third (the triangle inequality). First the opposite of this condition is checked: if any sum is equal to or smaller than the third side, there is no triangle. By De Morgan's law, the opposite of “all three inequalities are true” is “at least one is false”; that is why the terms are joined with ||. Then the type of triangle is tested from the narrow condition to the broad one: first equality of all three sides, then equality of any two sides.

import java.util.Scanner;

public class Triangle {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int a = in.nextInt(), b = in.nextInt(), c = in.nextInt();
        if (a + b <= c || a + c <= b || b + c <= a)
            System.out.println("Not a triangle");
        else if (a == b && b == c)
            System.out.println("Equilateral");
        else if (a == b || b == c || a == c)
            System.out.println("Isosceles");
        else
            System.out.println("Scalene");
    }
}

The program printed Equilateral for (3, 3, 3), Isosceles for (3, 3, 5) and (5, 3, 5), and Scalene for (3, 4, 5). For (1, 2, 3), since 1 + 2 = 3, it printed “Not a triangle”; these sides form a straight line. For (2, 9, 4), since 2 + 4 = 6 < 9, the same result came out. The equilateral condition must be asked before the isosceles one, because every equilateral triangle also satisfies the isosceles condition.

Example 7.5

A program that converts a day number from 1 to 7 into a day name and warns on invalid input.

Solution. A single integer has seven discrete values; a switch expression is made for exactly this job. Invalid input is caught by default. Because this is a switch expression, default is mandatory anyway.

import java.util.Scanner;

public class DayName {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int day = in.nextInt();
        String name = switch (day) {
            case 1 -> "Monday";
            case 2 -> "Tuesday";
            case 3 -> "Wednesday";
            case 4 -> "Thursday";
            case 5 -> "Friday";
            case 6 -> "Saturday";
            case 7 -> "Sunday";
            default -> "Invalid day number";
        };
        System.out.println(name);
    }
}

It printed Monday for 1, Friday for 5, and Sunday for 7; for 8 and 0 it printed “Invalid day number”.

Example 7.6

A program that finds the smaller of two numbers with the conditional operator and then extends this to three numbers.

Solution. The smaller of two numbers is a < b ? a : b. For three numbers, first the smaller of the first two is found, then this value is compared with the third. Using two separate variables is more readable than a one-line nested conditional operator.

import java.util.Scanner;

public class Smallest {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int a = in.nextInt(), b = in.nextInt(), c = in.nextInt();
        int ofTwo = a < b ? a : b;
        int ofThree = ofTwo < c ? ofTwo : c;
        System.out.println(ofTwo + " " + ofThree);
    }
}

For (7, 12, 5), the smaller of the first two is 7 and the smallest of the three is 5; the program printed “7 5”. For (4, 4, 9) it printed “4 4”, and for (−1, 8, −6) it printed “−1 −6”.

Example 7.7

A check for “score outside the range 0–100” is to be added to the letter-grade program. Where in the chain should this check be written?

Solution. At the very beginning of the chain. If the check were put at the end, an invalid score, for example 105, would satisfy the first condition (105 >= 90) and receive an A; the check would never get its turn. −5 would similarly receive an F. Filtering out invalid cases at the start of the chain makes the later conditions work only with valid scores.

import java.util.Scanner;

public class GradeWithRange {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int score = in.nextInt();
        if (score < 0 || score > 100)
            System.out.println("Invalid score");
        else if (score >= 90)
            System.out.println('A');
        else if (score >= 80)
            System.out.println('B');
        else if (score >= 70)
            System.out.println('C');
        else
            System.out.println('F');
    }
}

The program printed “Invalid score” for 105 and −5, A for 100 and 95, C for 75, and F for 0. The boundary values 0 and 100 are considered valid; because < and > are used in the condition, these two values do not fall into the “invalid” branch.

7.10Summary

  • Every algorithm can be written with three flows: the sequence structure, the selection structure, and the repetition structure. In a sequence, statements run once each in the order written; each statement uses the values left by the previous ones.
  • A condition is a boolean expression that produces the value true or false. Equality is tested with ==; = is an assignment, and if (x = 5) does not compile. The notation 10 < x < 20 does not compile either; the correct form is x > 10 && x < 20.
  • if runs its body if the condition is true; if-else runs exactly one of its two branches. Without braces, the body is a single statement; the compiler does not look at indentation. The semicolon in a line if (…); is an empty statement.
  • In an else-if chain, the conditions are tried from top to bottom; the first true branch runs and the rest are skipped. In a chain built on lower bounds, the thresholds are written from largest to smallest. Independent ifs, on the other hand, are all checked.
  • If the final else is deleted, a variable assigned in the branches causes the “might not have been initialized” error. Java does not allow an unassigned local variable to be read.
  • In a nested decision, the inner condition is checked only when the outer condition selects that branch. Deep nesting can be flattened with &&. A dangling else attaches to the nearest if that has no else; the ambiguity is removed with braces.
  • && requires both sides to be true, || requires at least one side to be true; ! reverses. Both short-circuit: if the result is already determined by the left side, the right side is not evaluated. That is why b != 0 && a / b > 1 is safe. The single-character & and | always evaluate both sides.
  • De Morgan's laws: !(a && b) = !a || !b, !(a || b) = !a && !b. The opposites of the comparisons: >= ↔ <, > ↔ <=, == ↔ !=.
  • The conditional operator condition ? v1 : v2 is an expression that produces a value; it is used for short selections between two values and groups from the right.
  • For strings, == compares references and equals compares content. A string read from the keyboard gives false when compared with == to a literal carrying the same text. Always compare strings with equals.
  • switch chooses among the discrete values of a single expression; case labels are constants. A switch expression produces a value and must cover all values; for int and String, default is mandatory. The value of a branch with a block is given with yield.
  • In a classic switch, without break execution falls through into the code of the next case. In the arrow form (->) there is no fall-through. For ranges and complex conditions if-else is suitable; for the discrete values of a single expression, switch is suitable.
  • Lessons of the examples: the even test is done with % 2 == 0, because in Java -7 % 2 = -1. The absolute value of Integer.MIN_VALUE overflows in int. Math.sqrt gives NaN for a negative number, and floating-point division by zero gives Infinity. In the “candidate and compare” pattern, the candidate is initialized with one of the inputs.

7.11Key terms

The key terms of this chapter are listed below.

  • control flow
  • control structure
  • sequence structure
  • selection structure
  • repetition structure
  • statement
  • expression
  • widening conversion
  • trace table
  • condition
  • boolean
  • comparison operator
  • if-else statement
  • branch
  • block
  • curly braces
  • empty statement
  • multiway decision
  • else-if chain
  • nested decision
  • dangling else
  • logical operator
  • short-circuit evaluation
  • De Morgan's laws
  • operator precedence
  • exception
  • conditional (ternary) operator
  • reference
  • string literal
  • string pool
  • heap
  • switch expression
  • switch statement
  • case label
  • arrow form (->)
  • fall-through
  • remainder
  • absolute value
  • overflow
  • compile error

7.12Try it yourself

  1. With p = 4 and q = 9, the line if (p > 3 || ++q > 0) p = p * 2; runs. What are p and q afterwards?

    Answer

    The left side 4 > 3 is true. || short-circuits and ++q never runs; q stays 9. Because the condition is true, p = 4 × 2 = 8. Result: p = 8, q = 9.

  2. With t = 15, what is the value of the expression t % 3 == 0 && t % 5 == 0 ? "FizzBuzz" : t % 3 == 0 ? "Fizz" : "other"? What happens for t = 9 and t = 7?

    Answer

    The conditional operator groups from the right; the expression reads “if the first condition is true, FizzBuzz; otherwise (if the second condition is true, Fizz; otherwise other)”. 15 is divisible by both 3 and 5: “FizzBuzz”. 9 is divisible by 3 but not by 5: the first condition is false and the second is true, “Fizz”. 7 is divisible by neither: “other”.

  3. What does the following code assign for score = 72? What happens for score = 90 and score = 40?

    if (score >= 50) {
        if (score >= 85) grade = "Excellent";
        else grade = "Pass";
    } else grade = "Fail";
    Answer

    For 72, the outer condition 72 >= 50 is true and the inner condition 72 >= 85 is false: grade = "Pass". For 90, both conditions are true: "Excellent". For 40, the outer condition is false and the inner if is never checked: "Fail". The braces attach the inner else to the inner if and the outer else to the outer if.

  4. How can the condition if (!(temp < 15 || rain)) be written so that the ! operator remains only in front of the boolean variable? Is the condition true for temp = 30, rain = false?

    Answer

    By De Morgan's law, || turns into && and each term is negated: temp >= 15 && !rain. The opposite of < is >=. For 30 and false, 30 >= 15 is true and !false is true; the condition is true. In the original form too, 30 < 15 is false, rain is false, their OR is false, and its negation is true.

  5. A classic switch has the lines case 1: score += 10;, case 2: score += 20; break;, case 3: score += 30;, default: score += 5;. score starts at 0 each time. What is score for k = 1, 2, 3, and 4?

    Answer

    k = 1: there is no break in case 1, so execution falls into case 2: 10 + 20 = 30, then break. k = 2: only 20. k = 3: there is no break in case 3, so execution falls into default: 30 + 5 = 35. k = 4: no case matches, default: 5. Result: 30, 20, 35, 5.

  6. With char grade = 'B';, what is the value of switch (grade) { case 'A', 'B' -> "good"; case 'C' -> "fair"; default -> "poor"; }? What happens if the default line is deleted from this expression?

    Answer

    'B' is in the list of the first case: the value is "good". There is no fall-through in the arrow form; the second case does not run. If default is deleted, the program does not compile: a char can take more than 65 thousand values and a switch expression must cover all values. The compiler gives the message “the switch expression does not cover all possible input values”.

  7. With a = 5 and b = 0, what do the lines if (b == 0 || a / b > 2) and if (b == 0 | a / b > 2) do?

    Answer

    In the first line the left side is true; || short-circuits and the division is never evaluated. The condition is true and the body runs. In the second line, | evaluates both sides: the integer division 5 / 0 throws ArithmeticException: / by zero and the program stops.

  8. The user types “Ada” on the keyboard and this text is read into the variable name. What are the values of name == "Ada", name.equals("ada"), and name.equalsIgnoreCase("ada")?

    Answer

    name == "Ada" is false: the string read from the keyboard is a new object, while the literal is in the pool; the references differ. name.equals("ada") is false: the contents differ in letter case (“A” ≠ “a”). name.equalsIgnoreCase("ada") is true: letter case is ignored.

7.13Further reading

  • Oracle, The Java Tutorials, the pages “The if-then and if-then-else Statements” and “The switch Statement”: Java's decision structures explained with official examples and short descriptions.
  • Oracle, Java Language Specification, Java SE 21 Edition, Chapter 14 (“Blocks, Statements, and Patterns”) and 15.28 (“switch Expressions”): the precise definitions of the dangling else rule, the exhaustiveness requirement of switch expressions, and yield.
  • R. Sedgewick, K. Wayne, Computer Science: An Interdisciplinary Approach (Addison-Wesley, 2016), Section 1.3: conditionals and loops explained with short examples from scientific computing; the quadratic equation example is worked there as well.
  • A. B. Downey, C. Mayfield, Think Java (2nd ed., O'Reilly, 2019), the chapter “Conditionals and Logic”: conditions, logical operators, and nested decisions explained plainly for beginners; the online version of the book is free.

7.14References

  1. P. Deitel, H. Deitel, Java: How to Program, Early Objects, 11th ed., Pearson, 2018.
  2. Y. D. Liang, Introduction to Java Programming and Data Structures, 13th ed., Pearson, 2024.
  3. Oracle, The Java Tutorials: The if-then and if-then-else Statements; The switch Statement.
  4. Oracle, Java Language Specification, Java SE 21 Edition, Chapter 14: Blocks, Statements, and Patterns.
  5. R. Sedgewick, K. Wayne, Computer Science: An Interdisciplinary Approach, Addison-Wesley, 2016: 1.3 Conditionals and Loops.
  6. A. B. Downey, C. Mayfield, Think Java, 2nd ed., O'Reilly, 2019 (free online version).

Related pages: Chapter 7 slides · Study questions · Decision Tracer simulator · Glossary · © Sercan Külcü. All rights reserved.