Object-Oriented Programming with Java · Lecture Notes
Chapter 3.1: Control Structures
If a program consisted only of lines running from top to bottom, it would do the same work in the same order on every run. It could not behave differently depending on what the user enters, and doing a job a thousand times would take a thousand lines. Control structures remove both limitations. Decision structures look at a condition and choose one of two or more paths. Loops repeat a group of statements as long as a condition holds. First sequential flow is covered, then if, if-else, the else if chain, nested decisions, and switch. After that come the for, while, and do-while loops, nested loops, and break and continue, which alter the flow in the middle of a loop. For every structure the code is traced line by line, the values of the variables are shown in tables, and the Java compiler’s real error messages are given. All the code was run with JDK 21, and the outputs are taken from those runs.
Learning outcomes
- Flow control
- Explain how sequential, decision, and loop structures direct the flow of a program.
- Decision structures
- Write conditional code with
if,if-else, theelse ifchain, nested decisions, and compound conditions using&&and||; predict the result of short-circuit evaluation. - switch-case
- Compare a value against constants; explain the job of
breakand the fall-through behavior; tell the classicswitchfrom the arrow-formswitchexpression. - Loops
- Choose among the
for,while, anddo-whileloops appropriately; avoid infinite loops and boundary errors. - Nested loops
- Work out how many times nested loops run in pattern, table, and digit examples.
- Tracing
- Trace a program step by step to find the values of the variables and the screen output in advance; show the effect of
breakandcontinue.
3.1.1Control structures
Java source code consists of statements. A variable declaration, an assignment, or a println call is a statement, and each ends with a semicolon. The compiler translates these statements to bytecode in the order they are written. At run time, it is the control structures that determine which statement runs, when, and how many times.
A control structure is a language construct that determines in what order and how many times statements run. The path the program follows according to this order is called its flow.
3.1.1.1Three basic structures
Java has three basic control structures (Figure 3.1.1). In sequential execution, statements run from top to bottom, once each. In decision structures a condition is examined and one of two or more paths is chosen; Java’s forms are if-else and switch. In loops the same group of statements is repeated as long as a condition holds; Java has the for, while, and do-while loops.
Small as they look, these three structures are enough to write every known algorithm. This result rests on the structured program theorem shown by Böhm and Jacopini in 1966: by combining sequence, selection, and repetition, every computable task can be expressed. The structures can also be nested. A loop body can contain a decision, and a branch of a decision can contain a loop. Real programs are the result of this nesting.
Decisions give a program flexibility. The same program answers different inputs differently: it turns a negative number positive, and it writes B for a student who scores 85 and F for one who scores 45. Loops, for their part, shorten repetitive work. To add the numbers from 1 to 1,000,000, a three-line loop is enough, not a million lines. The code gets shorter and easier to change: to raise the bound from 1,000,000 to 2,000,000, only one number changes.
3.1.1.2Sequential execution
Every program without a control structure is sequential. The code runs line by line from top to bottom, and no line starts before the previous one has finished. The four lines below are the smallest example of this order:
int x = 5;
int y = 10;
int result = x + y;
System.out.println(result);The first line sets aside an int variable named x and writes 5 into it. The second line does the same for y with 10. The third line reads the results of the previous two lines, computes 5 + 10 = 15, and writes it into the variable result. The last line prints this value on the screen. Table 3.1.1 shows which variables are in memory after each line. An empty cell means the variable has not yet been declared.
| Line | Statement | x | y | result | Screen |
|---|---|---|---|---|---|
| 1 | int x = 5; | 5 | |||
| 2 | int y = 10; | 5 | 10 | ||
| 3 | int result = x + y; | 5 | 10 | 15 | |
| 4 | System.out.println(result); | 5 | 10 | 15 | 15 |
result box was computed from the values written by the previous two lines.The importance of order shows in an experiment. Move the third line to the very beginning: when the line int result = x + y; runs, x and y are not yet declared. In this case Java does not compile the program at all and gives the message cannot find symbol. In sequential structure each line depends on the state left by the lines before it.
Reading a variable without giving it a value. If System.out.println(result); is written right after the line int result;, the compiler reports the error variable result might not have been initialized. At compile time Java checks that a local variable certainly receives a value before it is read. This check matters most in decision structures that give the variable a value in only some of their branches.
3.1.2Making decisions with if
Decision making means the program chooses at run time which path to follow. The choice cannot be made at compile time, because it often depends on input: the number the user types, the contents of a file that is read, a measurement from a sensor. Its counterpart in everyday life is a sign at a fork in the road: “If the weather is rainy, take an umbrella; if not, don’t.” In Java, decisions are written with if-else and switch. This section covers the if family, and the following sections cover multiway decisions and switch.
3.1.2.1Conditions and comparison operators
A condition is a logical (boolean) expression whose result is true or false. In Java the type of a condition is always boolean.
Most conditions are built by comparing two values. Java’s six comparison operators are given in Table 3.1.2, with examples for x = 7.
| Operator | Meaning | Example | Result |
|---|---|---|---|
== | equal to | x == 7 | true |
!= | not equal to | x != 7 | false |
< | less than | x < 10 | true |
> | greater than | x > 10 | false |
<= | less than or equal to | x <= 7 | true |
>= | greater than or equal to | x >= 8 | false |
No space goes between the characters of a two-character operator: if < = is written, the compiler reads it as two separate tokens and reports an error. The mathematical signs ≤, ≥, and ≠ have no counterpart in Java; <=, >=, and != are used instead.
The most important distinction is between = and ==. A single equals sign is assignment: it writes the value on the right into the variable on the left. A double equals sign is comparison: it asks whether two values are equal and produces a boolean. In C, if (x = 7) compiles and is always taken as true, which makes it a very insidious source of bugs there. Java, on the other hand, requires the condition to be boolean. Because the value of the expression x = 7 is the int 7, the program does not compile:
error: incompatible types: int cannot be converted to boolean
if (x = 7) {
^This rule protects only numeric variables such as int. If the variable itself is boolean, if (done = true) compiles, writes true into done, and the condition always comes out true. The easiest way to avoid this trap is never to compare a boolean variable with anything: if (done) and if (!done) are enough.
3.1.2.2The if-else structure
The if statement is a decision statement that runs a block if the condition is true. The optional else branch gives the block to run when the condition is false.
if (condition) {
// runs if the condition is true
} else {
// runs if the condition is false
}The structure works in three steps. First the condition in parentheses is evaluated. If the condition is true, the if block runs and the else block is skipped. If the condition is false, the if block is skipped and the else block runs. In both cases the flow rejoins at the end of the structure and continues with the next statement (Figure 3.1.3). At most one of the two blocks runs; if there is an else, exactly one runs.
if-else flow diagram. If the condition is true (Y) the if block runs, and if false (N) the else block runs; the two paths join and the flow moves on to the next statement.There are two writing rules. The condition is always written in parentheses: if condition does not compile, if (condition) does. Blocks are opened and closed with braces. The group of statements between braces is called a block. A variable declared inside a block lives only in that block; when the block is left, its name is gone too.
3.1.2.3if alone, and braces
The else branch is optional. If there is nothing special to do when the condition is false, only if is written:
int temp = 35;
if (temp > 30) {
System.out.println("It's hot!");
}
System.out.println("The program continues.");It's hot!
The program continues.Because temp is 35, 35 > 30 is true and the block runs. Then the flow moves to the statement after the if. If the temperature were 20, the condition would be false, the block would be skipped, and only “The program continues.” would appear on the screen. A statement outside the if structure runs in every case, independent of the result of the condition.
The braces may be left out when the block has a single statement. Java’s rule is this: without braces, only the first statement is attached to the if. Indentation, that is, the spaces at the beginning of a line, has no meaning for Java. For someone used to languages like Python, which build blocks by indentation, this gives rise to the trap below:
int temp = 35;
if (temp > 40)
System.out.println("Very hot!");
System.out.println("Drink water.");Drink water.35 > 40 is false, so “Very hot!” is not printed. The line “Drink water.” is not part of the if, even though the two lines stand at the same indentation. The structure the compiler sees is: if (temp > 40) println("Very hot!"); followed by a separate, unconditional println("Drink water.");. If the programmer’s intention is to make both lines depend on the condition, only braces can do that. It is therefore a good habit to use { } even for one-line blocks. When a second line is added to the block later, the same mistake does not arise again.
Putting a semicolon after the condition. if (x > 5); { … } compiles, but the semicolon by itself is an empty statement. The compiler reads this as “if the condition is true, do nothing.” The block that follows is not attached to the if and runs in every case. Tried with x = 3, if (x > 5); { System.out.println("x is greater than five"); } still prints “x is greater than five.” The compiler gives no warning for this line either.
3.1.2.4An age check
The first complete decision example is a six-line piece of code that checks the age for a driver’s license:
int age = 18;
if (age >= 18) {
System.out.println("You can get a license.");
} else {
System.out.println("You cannot get a license.");
}The first line assigns 18 to the variable age. In the second line the condition is evaluated: 18 >= 18 is true, because >= includes equality. In the flow diagram this means going to the yes (Y) branch (Figure 3.1.4). The third line runs and “You can get a license.” is printed. The else block, that is, the fifth line, is skipped.
age = 18 the condition is true and the flow goes to the Y branch, drawn in bold.age | age >= 18 | Block that runs | Screen |
|---|---|---|---|
| 16 | false | else | You cannot get a license. |
| 18 | true | if | You can get a license. |
| 25 | true | if | You can get a license. |
The 18 in the table is a boundary value: the point where the condition changes from true to false. Reliable code should be tried on both sides of the boundary and exactly on it. If the condition had mistakenly been written age > 18, 16 and 25 would give the right result and only 18 the wrong one. A mistake of this kind shows up only in a test with the boundary value.
3.1.2.5Absolute value
The second example reads a floating-point number from the user and prints its absolute value. The absolute value of a number is the number with its sign changed if it is negative, and the number itself otherwise: |−7.5| = 7.5 and |3| = 3.
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
double num = scanner.nextDouble();
double absValue;
if (num < 0) {
absValue = -num;
} else {
absValue = num;
}
System.out.println("Absolute value: " + absValue);The code assumes that the line import java.util.Scanner; is at the top of the file. The first line creates a Scanner object to read from the keyboard. The second line tells the user what to enter. Here print is used, not println: print does not move to a new line, and the cursor waits right next to the question. In the third line nextDouble() reads the number the user typed.
The fourth line declares the variable absValue but gives it no value. The if-else below will give it one. Java accepts this line because each of the two branches writes a value into the variable. The compiler can check this: whichever branch runs, by the time the last line is reached the variable has certainly received a value. If the else branch were deleted, the compiler would report variable absValue might not have been initialized for the last line.
num < 0 is true; in the highlighted box absValue = -num runs.Suppose the user enters −7.5. On the fifth line -7.5 < 0 is true. On the sixth line the expression -num computes −(−7.5) = 7.5 and writes it into absValue. The else block is skipped. The last line prints Absolute value: 7.5. Table 3.1.4 summarizes running the same program with four inputs.
| From the keyboard | num | num < 0 | Screen |
|---|---|---|---|
| -7,5 | −7.5 | true | Absolute value: 7.5 |
| 7,5 | 7.5 | false | Absolute value: 7.5 |
| 0 | 0.0 | false | Absolute value: 0.0 |
| -7.5 | — | — | InputMismatchException |
The last row is a detail specific to Java. Scanner reads numbers according to the computer’s regional setting. In the Turkish setting the decimal separator is a comma. That is why -7,5 is accepted, while -7.5 is not taken as a number and the program stops with this message:
Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:947)
at java.base/java.util.Scanner.next(Scanner.java:1602)
at java.base/java.util.Scanner.nextDouble(Scanner.java:2573)Reading follows the regional setting; writing does not. println always writes a double value with a period: 7.5. This is why the same program shows a comma on input and a period on output. If reading is to use a period as well, scanner.useLocale(java.util.Locale.US) is called after the Scanner is created.
3.1.3Multiway decisions
An if-else structure chooses between two paths. In real problems there are often more options. A number can be positive, negative, or zero; a grade can correspond to A, B, C, D, or F. Java offers two tools for these cases: the else if chain, which strings conditions one after another, and nested structure, which places decisions inside one another. At the end of the section come the && and || operators, which combine several conditions in one expression, and the conditional operator ?:.
3.1.3.1The else-if chain
An else-if chain is a structure that tries the conditions in order from top to bottom and runs the block of the first true condition. If no condition is true, the final else block, if there is one, runs.
The complete program below finds the sign of a number. The three possible outcomes are separated by two conditions and a final else:
import java.util.Scanner;
public class PositiveNegative {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
double num = scanner.nextDouble();
if (num > 0) {
System.out.println("Positive.");
} else if (num < 0) {
System.out.println("Negative.");
} else {
System.out.println("Zero.");
}
}
}When the program is run with three different inputs, it gives these outputs:
Enter a number: 4
Positive.Enter a number: -2
Negative.Enter a number: 0
Zero.When 4 is entered, the first condition 4 > 0 is true. “Positive.” is printed and the rest of the chain is never looked at. When −2 is entered, the first condition is false and the flow moves to the second condition: -2 < 0 is true and “Negative.” is printed. When 0 is entered, both conditions are false and the last else runs. None of the three branches can run at the same time: the moment one branch is selected, the chain ends.
else if is not a separate keyword in Java. The structure is just a new if written inside an else branch. The form of the program in the compiler’s eyes is: if (num > 0) { … } else { if (num < 0) { … } else { … } }. Programmers write it at a single level, one below another, because that is more readable. Each link in the chain is evaluated knowing that all the conditions before it were false. Only non-positive numbers reach the condition num < 0 in the second link.
3.1.3.2Tracing the letter-grade chain
The letter-grade example shows best how the chain uses order. A numeric grade of 90 or above gets A, 80–89 gets B, 70–79 gets C, 60–69 gets D, and below 60 gets F.
int grade = 75;
if (grade >= 90) {
System.out.println("A");
} else if (grade >= 80) {
System.out.println("B");
} else if (grade >= 70) {
System.out.println("C");
} else if (grade >= 60) {
System.out.println("D");
} else {
System.out.println("F");
}For grade = 75 the flow is as follows. The first condition 75 >= 90 is false and the flow moves to the next else if. 75 >= 80 is false too. 75 >= 70 is true: the first true condition has been found. “C” is printed. The remaining condition, grade >= 60, is never tested (Figure 3.1.6).
else-if chain, grade = 75. At the first two diamonds the flow goes to the N branch; at the third diamond (grade ≥ 70) the condition is true and the flow moves to the “Print C” box.grade | >= 90 | >= 80 | >= 70 | >= 60 | Conditions tested | Screen |
|---|---|---|---|---|---|---|
| 95 | true | — | — | — | 1 | A |
| 80 | false | true | — | — | 2 | B |
| 75 | false | false | true | — | 3 | C |
| 60 | false | false | false | true | 4 | D |
| 45 | false | false | false | false | 4 | F |
Notice that upper bounds such as grade < 90 are not written in the conditions. The link else if (grade >= 80) is reached only if grade >= 90 is false; so at this point the grade is already below 90. The chain takes its upper bound from the order itself. That is why the order of the conditions matters. Let the same four conditions be written in reverse order:
if (grade >= 60) {
letter = "D";
} else if (grade >= 70) {
letter = "C";
} else if (grade >= 90) {
letter = "A";
} else {
letter = "F";
}This code produces “D” for 95 and for 75 alike. Every number from 60 up satisfies the first condition, and the chain ends at the first link. No value can reach the grade >= 90 link. The compiler does not catch this mistake, because the code follows the rules of Java. What is wrong is the logic. The rule is simple: in a chain written with >=, the thresholds go from largest to smallest; in a chain written with <, from smallest to largest.
Writing independent if statements one after another instead of a chain. In code written as if (grade >= 90) letter = "A"; if (grade >= 80) letter = "B"; if (grade >= 70) letter = "C";, each if is tested separately. For 95, first "A", then "B", then "C" is assigned, and the result is C. The word else carries the meaning “if the previous conditions were false”; without it the conditions do not exclude one another.
3.1.3.3Nested decisions
A nested decision is a decision structure written inside the block of another decision structure. The inner decision is tested only when the outer condition selects the branch that contains it.
if (cond1) {
if (cond2) {
// cond1 AND cond2 true
}
} else {
// cond1 false
}Nested structure is useful when a second question is to be asked depending on the answer to the first (Figure 3.1.7). The body of the inner if is entered only if cond1 and cond2 are both true. If cond1 is false, the inner if is never tested and the outer else runs directly.
cond1 is true, cond2 is tested; if false, the outer else block runs. If cond1 is true and cond2 is false, no block runs.A two-level version of the letter-grade example makes the structure concrete. First it checks whether the student passes, and for those who pass it separates A from B:
int grade = 85;
if (grade >= 60) {
if (grade >= 90) {
System.out.println("Letter grade: A");
} else {
System.out.println("Letter grade: B");
}
} else {
System.out.println("Letter grade: F");
}For grade = 85 the outer condition 85 >= 60 is true and the outer if block is entered. There the inner condition is tested: 85 >= 90 is false, the flow goes to the inner else, and “Letter grade: B” is printed. The outer else is skipped (Figure 3.1.8). With grade = 45, the outer condition would be false, the inner if would never be tested, and “Letter grade: F” would be printed directly.
grade = 85. At the outer diamond the flow goes to the Y branch, at the inner diamond to the N branch, and the “Print B” box runs.Very deeply nested structures lead to code that is hard to read. In an if nested four or five levels deep, you have to count braces to find which else belongs to which if. There are two remedies. The first is proper indentation: each inner level starts four spaces further in. The second is to flatten the structure. Code that cares only about the case where two conditions are both true can be reduced to a single if with &&: if (age >= 18) { if (hasLicense) … } and if (age >= 18 && hasLicense) … do the same job.
The dangling else problem. In nested if statements without braces, it can seem unclear which if an else belongs to. Java’s rule is exact: an else attaches to the nearest preceding if that does not yet have an else. In the code below the indentation makes the else look attached to the inner if, and the rule gives the same result:
int x = 7;
if (x > 5)
if (x > 10)
System.out.println("A");
else
System.out.println("B");For x = 7, 7 > 5 is true, the inner condition 7 > 10 is false, and the else of the inner if prints “B”. When the same code is run with x = 3, it prints nothing: the outer condition is false and the outer if has no else. Even if the else is shifted left to the indentation of the outer if, the result does not change; indentation means nothing to the compiler. If the else is really meant to attach to the outer if, the inner if is closed with braces:
int x = 7;
if (x > 5) {
if (x > 10) {
System.out.println("A");
}
} else {
System.out.println("B");
}This version prints nothing for x = 7 and “B” for x = 3. The two pieces of code consist of the same lines, but the braces have changed the owner of the else.
3.1.3.4Compound conditions and short-circuiting
Several conditions are combined into a single condition with logical operators. Java has three logical operators: && (and), || (or), and ! (not). a && b is true only if both sides are true. a || b is true if at least one of the sides is true. !a is the opposite of a.
a | b | a && b | a || b | !a |
|---|---|---|---|---|
true | true | true | true | false |
true | false | false | true | false |
false | true | false | true | true |
false | false | false | false | true |
The most common use of logical operators is range checking. Whether a grade lies between 60 and 89 cannot be written as in mathematics, 60 <= grade < 90. Java reads this expression from left to right: first 60 <= grade is computed and a boolean results. Then this boolean is compared with 90, but one cannot ask whether a boolean is less than 90. The compiler gives this message:
error: bad operand types for binary operator '<'
first type: boolean
second type: intThe correct form joins the two comparisons with &&: grade >= 60 && grade < 90. Using || here is also a common mistake. grade >= 60 || grade < 90 is true for every number: every number below 60 is also below 90.
Short-circuit evaluation: && and || evaluate the left side first. If the result is already determined by the left side alone, the right side is not evaluated at all. In &&, if the left side is false the result is false; in ||, if the left side is true the result is true.
Short-circuiting is more than a detail of speed; it changes the behavior of the program. The code below shows this in three lines:
int a = 10, b = 0, count = 0;
boolean s1 = b != 0 && a / b > 2;
boolean s2 = b == 0 || ++count > 0;
boolean s3 = b == 0 && ++count > 0;
System.out.println(s1 + " " + s2 + " " + s3);
System.out.println("count = " + count);false true true
count = 1At the start b = 0. If a / b were evaluated, a division-by-zero error (ArithmeticException) would occur. count is there to count whether the right-hand sides run: each time ++count runs, it increases by 1.
s1:&&evaluates the left side first:b != 0is false. If the left side is false, the result of&&is false whatever the right side is.a / b > 2is never evaluated and no error occurs.s1 = false.s2: for||the left sideb == 0is true. The result is already true;++countdoes not run andcountstays 0.s2 = true.s3:&&again; the left sideb == 0is true. The result is not yet determined, so the right side must be evaluated as well.++countruns andcountbecomes 1;1 > 0is true.s3 = true.
s1 has been computed; because the left side is false, the right side is marked “skipped.” Bottom: all three lines are finished; only the right side of s3 ran and count became 1.In the end only one of the three right-hand sides ran. This behavior has two sides. The useful side is guarding a dangerous operation, as in s1. When b != 0 && a / b > 2 is written, the division is performed only if the denominator is nonzero. The same pattern is common with objects: s != null && s.length() > 0. The dangerous side is side effects. If an operation that changes a variable, such as ++count, is written on the right-hand side, whether it runs depends on the left side. A person reading the code easily misses this. The safest course is not to write operations with side effects to the right of && and ||.
Java has two more operators that do not short-circuit: & and |. When used with boolean values they always evaluate both sides. If b != 0 & a / b > 2 is written, the division is performed even though the left side is false, and the program stops with java.lang.ArithmeticException: / by zero. In conditions, writing a single & is most often a typing mistake.
3.1.3.5The conditional operator
Choosing one of two values according to a condition is a very common task. For it an if-else can be written:
int a = 17, b = 42;
int max;
if (a > b) {
max = a;
} else {
max = b;
}
System.out.println(max);Java offers the conditional operator, which does the same job in a single expression. Because it has three parts, it is also called the ternary operator: condition ? value1 : value2. If the condition is true, the value of the expression is value1; if false, value2.
int a = 17, b = 42;
int max = (a > b) ? a : b;
System.out.println(max);Because 17 > 42 is false, the second value is chosen and 42 is printed. if-else is a statement and does a job. ?: is an expression and produces a value. It can therefore be written on the right of an assignment, as the argument of a method, or inside a string concatenation: System.out.println(grade >= 60 ? "passed" : "failed");. Nested conditional operators (a ? b : c ? d : e) quickly become unreadable; with more than two alternatives an else if chain is preferred. To find the larger of two numbers, Java’s ready-made Math.max(a, b) method can also be used.
3.1.4switch-case
Some decisions always ask whether the same variable equals different constant values: is the month 1, 2, 3…? Is the operation '+' or '-'? Such decisions can also be written with an else if chain, but in a twelve-link chain month == is repeated in every link. The switch structure is designed for this situation.
3.1.4.1Structure and operation
The switch statement compares the value of the expression in parentheses with the constants in the case labels and continues with the code under the matching label. If no label matches, the code under the default label, if there is one, runs.
switch (variable) { // value being checked
case value1: // one value per case
// statements 1
break;
case value2:
// statements 2
break;
// ...
default: // if nothing matches
// default statements (optional)
}The expression in parentheses is called the selector. The selector is evaluated once. Its value is compared with the case labels from top to bottom. When a matching label is found, the statements under it run. On reaching break, the switch is left and the flow moves to the statement after the closing brace. If no label matches, the default section runs. If there is no default either, the switch is left without anything being done (Figure 3.1.10).
switch-case works. The selector is compared in turn with value1 and value2. The statements of the matching case run and the switch is left with break; if none matches, the default statements run.An everyday analogy is the buttons in an elevator. The floor number pressed selects the floor to go to directly. The elevator does not stop at every floor to ask “is this the 3rd floor?” A switch often works that way too: conceptually the labels can be thought of as tried in turn, but if the labels are closely packed integers, the compiler builds a jump table and jumps directly to the right label.
3.1.4.2Determining the season
The code that finds the season from the month number shows all the parts of switch together:
int month = 4;
String season;
switch (month) {
case 3: case 4: case 5:
season = "Spring";
break;
case 6: case 7: case 8:
season = "Summer";
break;
case 9: case 10: case 11:
season = "Autumn";
break;
case 12: case 1: case 2:
season = "Winter";
break;
default:
season = "Unknown";
}
System.out.println(month + ": " + season);4: SpringThe first line assigns 4 to month. The second line declares season but gives it no value. On the third line the selector month is evaluated once: its value is 4. Then the matching label is looked for. The fourth line has three labels written on one line: case 3: case 4: case 5:. 4 matches one of them. There is a single piece of code under the three labels; whichever matches, the flow drops into the same code. "Spring" is assigned to season. break carries the flow to just past the closing brace of the switch. The last line prints “4: Spring.”
case groups in the season example. month = 4 matches the first group and season becomes “Spring.”The default branch does two jobs here. The first is to give an answer for invalid month numbers such as 0, 13, or −5. The second is to let the code pass the compiler’s variable check. If season were assigned only in the case branches, the compiler would reason as follows: if the selector matches no label, season never gets a value. The read on the last line is therefore rejected:
error: variable season might not have been initialized
System.out.println(season);
^Once default is added, every path out of the switch has written a value into season and the error disappears. When all month values from 0 to 13 are tried, “Unknown” is printed for 0 and 13 and the correct season for the others.
3.1.4.3Fall-through
Fall-through is the running of the code of the case labels below as well, after the code of a case that does not end with break.
A case label is not a comparison statement but an entry point. The switch only chooses where to start. Once the flow has entered, it does not look at the labels below; it moves line by line until a break or the end of the switch. In the code below, the first two case labels have no break:
int day = 2;
switch (day) {
case 1:
System.out.println("Monday");
case 2:
System.out.println("Tuesday");
case 3:
System.out.println("Wednesday");
break;
default:
System.out.println("Other day");
}
System.out.println("switch done");Tuesday
Wednesday
switch doneWith day = 2 the selector is evaluated. case 1 is skipped, case 2 matches, and “Tuesday” is printed. There is no break here. The flow arrives at the line case 3: below. This label does not ask “is the day 3?”; the flow falls into the code under it and “Wednesday” is printed too, although the day is not 3. The break that follows leaves the switch, and default does not run. Finally “switch done” is printed (Figure 3.1.12).
case 2 ran (green), and because there is no break the flow falls into case 3 (highlighted). case 1 was skipped.day | Entry point | Code that runs | Screen |
|---|---|---|---|
| 1 | case 1 | case 1, case 2, case 3, break | Monday, Tuesday, Wednesday |
| 2 | case 2 | case 2, case 3, break | Tuesday, Wednesday |
| 5 | default | default | Other day |
Fall-through is not always a mistake. The line case 3: case 4: case 5: in the season example is in fact a deliberate use of this behavior: case 3 and case 4 are empty labels and the flow falls into the common code below. The mistake is forgetting break where the fall-through is not wanted. The compiler gives no warning in that case. Deliberately left fall-throughs are therefore usually marked with a comment: // no break: fall-through intended.
What does the following code print?
int k = 2;
int points = 0;
switch (k) {
case 1: points += 10;
case 2: points += 20;
case 3: points += 30; break;
case 4: points += 40;
}
System.out.println(points);The selector is 2; the flow enters at case 2 and points becomes 20. Because there is no break, it falls into case 3 and points becomes 50. The break on this line leaves the switch; case 4 does not run. 50 is printed. With k = 1 it would print 10 + 20 + 30 = 60, and with k = 4 it would print 40.
3.1.4.4switch with char and String
The selector does not have to be an int. A simple calculator can be written with a char selector:
int a = 12, b = 4;
char op = '*';
int result;
switch (op) {
case '+': result = a + b; break;
case '-': result = a - b; break;
case '*': result = a * b; break;
case '/': result = a / b; break;
default:
System.out.println("Bad operator");
result = 0;
}
System.out.println(a + " " + op + " " + b
+ " = " + result);12 * 4 = 48char literals are written in single quotes: '+', '*'. Short case branches can be fitted on one line: case '+': result = a + b; break;. Line breaks do not matter to the compiler. For op = '*' the third label matches, result becomes 48, and “12 * 4 = 48” is printed. For an undefined operation such as op = '%', default runs: “Bad operator” is printed, followed by “12 % 4 = 0.” The line result = 0; in default is required here as well; without it the last line gives a might not have been initialized error.
There is a danger in this code that is easy to overlook: for b = 0 and op = '/', a / b runs and the program stops with ArithmeticException: / by zero. In a real calculator the '/' branch would first have to check the condition b != 0.
Since Java 7 the selector can also be a String:
String command = "stop";
switch (command) {
case "start":
System.out.println("Engine started");
break;
case "stop":
System.out.println("Engine stopped");
break;
default:
System.out.println("Unknown command");
}Engine stoppedThe labels are string literals in double quotes. The comparison is made on content, as the equals method does; it is not the object-identity comparison done by ==. The comparison is case-sensitive: for command = "Stop" no label matches and “Unknown command” is printed. If the text the user types is converted to lowercase first, the problem goes away:
String command = "Stop";
switch (command.toLowerCase()) {
case "start":
System.out.println("Engine started");
break;
case "stop":
System.out.println("Engine stopped");
break;
default:
System.out.println("Unknown command");
}This code prints “Engine stopped.” With Turkish text, toLowerCase() depends on the computer’s regional setting: in the Turkish setting the letter “I” becomes “ı.” For commands made only of ASCII letters, using toLowerCase(java.util.Locale.ROOT) removes this difference.
3.1.4.5switch rules
The rules of the classic switch exist so that the structure can be turned into a jump table. Each rule is checked with a compiler message (Table 3.1.8).
- The type of the selector. It can be
byte,short,char,int, their wrappers (Byte,Short,Character,Integer),String, andenum. A classicswitchcannot be written withlong,float,double, orboolean. - Labels are constants.
casevalues must be constants known at compile time:5,'a',"stop", or afinalvariable with a constant value. An ordinary variable cannot be a label. - Labels are unique. The same value cannot be used in two
caselabels. - Only equality is tested. A range (
month >= 3 && month <= 5) or a compound condition cannot be written in acase.if-elseis needed for those.
| Code | Compiler message |
|---|---|
double d = 2.5; switch (d) { … } | error: selector type double is not allowed |
long d = 2; switch (d) { … } | error: selector type long is not allowed |
int b = 2; switch (a) { case b: break; } | error: constant expression required |
switch (a) { case 1: break; case 1: break; } | error: duplicate case label |
If the b in the third row were declared as final int b = 2;, the code would compile. The value of a final variable cannot change, and if it is given by a constant expression the compiler uses it like a constant. Why there is such a rule becomes clear when you think of the labels being written into a table at compile time: the compiler building the table cannot know a value that might change at run time.
3.1.4.6switch or else-if?
The two structures do the same job with different strengths. Table 3.1.9 brings the differences together.
if-else / else if | switch-case | |
|---|---|---|
| What is tested? | Any boolean condition: ranges, compound conditions, different variables | Equality of a single expression with constant values |
| Flexibility | More flexible | Only certain types and constant case values |
| With many alternatives | Long chains can look complicated | A neat, readable list |
| Trap | If the order of conditions is wrong, the wrong branch is chosen | If break is forgotten, execution falls into the case labels below |
| Example | if (grade >= 90) … else if (grade >= 80) … | switch (month) { case 3: … } |
Every switch can be written as an else if chain: each case becomes an == comparison and default becomes the last else. The reverse is not always possible. Ranges such as grade >= 90 in the letter-grade example can be carried over to switch only by writing eleven separate labels from 90 to 100. The rule of choice can be summed up as follows: use switch if a single variable is compared with a few constants, and if-else if there are ranges or several variables.
3.1.4.7The switch expression
Java 14 added a new form to switch. The season example is written in this form as follows:
int month = 11;
String season = switch (month) {
case 3, 4, 5 -> "Spring";
case 6, 7, 8 -> "Summer";
case 9, 10, 11 -> "Autumn";
case 12, 1, 2 -> "Winter";
default -> "Unknown";
};
System.out.println(season);AutumnA switch expression is the form of switch that uses arrow (->) labels and produces a value. It has been a standard part of the language since Java 14.
The new form has four differences. First, a case can take several values separated by commas: case 3, 4, 5. Second, there is no fall-through in the arrow form. The expression or block on the right of each branch runs and the switch ends; break is not needed. Third, switch produces a value, and this value can be assigned directly to a variable. Because the assignment is a statement, a semicolon follows the closing brace: };. Fourth, the expression form must cover all possibilities. When the selector is an int, the possible values are practically endless, so default is required. If default is deleted, the compiler gives this message:
error: the switch expression does not cover all possible input valuesIf a branch needs several statements instead of a single value, the right-hand side becomes a block and the value to be produced is given with yield:
int day = 3;
String type = switch (day) {
case 6, 7 -> "weekend";
default -> {
System.out.println("counting working days");
yield "weekday";
}
};
System.out.println(type);counting working days
weekdayThe arrow form and the colon form cannot be mixed in the same switch; the compiler gives the message different case kinds used in the switch. The arrow form can also be used as a statement that produces no value: switch (day) { case 6, 7 -> System.out.println("holiday"); default -> System.out.println("work"); }. In this course the classic form is the basis, because most old code is written with it and the fall-through behavior is seen only in it. In new code written for Java 14 and later, the arrow form is safer: the mistake of forgetting break cannot be made in this form.
3.1.5Application: temperature conversion
Before moving from decisions to loops, a small sequential program shows how formulas are translated to Java. The problem is to convert a Celsius value to the Fahrenheit and Kelvin scales. A few common points of the three scales are given in Table 3.1.10.
| Celsius (°C) | Fahrenheit (°F) | Kelvin (K) | Meaning |
|---|---|---|---|
| −40 | −40 | 233.15 | The point where the two scales meet |
| 0 | 32 | 273.15 | Freezing point of water |
| 25 | 77 | 298.15 | Room temperature |
| 100 | 212 | 373.15 | Boiling point of water (at sea level) |
The conversion formulas are: °F = (°C × 1.8) + 32, °C = (°F − 32) / 1.8, and K = °C + 273.15. The Java program computes the first and last formulas for a single value:
public class Program {
public static void main(String[] args) {
double celsius = 25.0;
double fahrenheit = (celsius * 1.8) + 32;
double kelvin = celsius + 273.15;
System.out.println(celsius + " °C = " + fahrenheit + " °F = " + kelvin + " K");
}
}25.0 °C = 77.0 °F = 298.15 KThe program is sequential: three lines of computation and one line of printing; there is no decision or loop. double is used for floating-point values. The 1.8 and 273.15 in the code are Java literals, and in code the decimal separator is always the period. The parentheses show the precedence explicitly: first celsius * 1.8, then + 32. Because multiplication is done before addition, the result would be the same without parentheses, but they make the formula easier to read. The + signs in the printing line are not addition but concatenation: a + next to a string (String) converts the number to text and appends it. double values are written in the form 25.0.
Floating-point numbers cannot hold every value exactly. Because 1.8 cannot be written as a finite fraction in binary, some results carry a small error. For 37 °C the expression celsius * 1.8 + 32 prints 98.60000000000001; for −40 °C, celsius + 273.15 prints 233.14999999999998. These numbers are not wrong; they only carry a rounding trace in the last digit. To make them look right on screen, they are printed rounded to two digits with System.out.printf("%.2f%n", kelvin). Unlike println, printf follows the regional setting: on a computer with the Turkish setting the output is 233,15.
Writing the formula with integers. For int c = 37; the expression 9 / 5 * c + 32 gives 69: 9 / 5 is the quotient of two int values, the fraction is discarded, and the result is 1. c / 5 * 9 + 32 gives 95 because of 37 / 5 = 7. c * 9 / 5 + 32 is computed from left to right: 333 / 5 = 66, result 98; still 98, not 98.6. For a fractional result at least one of the operands must be double: c * 1.8 + 32 or c * 9.0 / 5 + 32.
3.1.6Loops and for
A loop is a control structure that repeats a group of statements as long as a condition holds. The repeated group of statements is called the body, and each run of the body is called an iteration.
The everyday counterpart of a loop is running ten laps on a track. The same movements are made on each lap and the lap counter goes up by one. When the counter reaches ten, the run ends. It is the same in a program: the body stays the same, one or a few variables change on each iteration, and a condition says when to stop. Loops are also used to process a collection of data in order. Looking at every element of an array, reading every line of a file, or averaging a series of measurements is done with a loop. Instead of writing the same line 100 times, a single loop is written; the code gets shorter and the number of repetitions is set by changing a single number.
3.1.6.1Kinds of loops
Java has three loops. All three rest on the same idea; the difference is where the condition is tested and where the initialization and update are written.
for: used when the number of iterations is known. The initialization, condition, and update are on a single line:for (int i = 0; i < 5; i++) { … }.while: runs as long as a condition holds; the number of iterations may not be known in advance:while (condition) { … }.do-while: the condition is written at the end; the body runs at least once:do { … } while (condition);.
for and while test the condition before the body; the body may never run (at least 0 iterations). do-while tests the condition after the body; the body runs at least once.3.1.6.2The for loop
A for loop is a loop that gathers the initialization, condition, and update steps in its header on a single line, separated by semicolons.
for header. ① The initialization runs once at the very start. ② The condition is tested before every iteration. ③ The update runs at the end of every iteration. ④ The body is the repeated operation.The three parts of the header run at different times (Figure 3.1.15). The order of execution is: 1 → 2 → 4 → 3 → 2 → 4 → 3 → … → 2 false → leave the loop. That is, the initialization once, then on every iteration the condition, the body, and the update. When the condition comes out false, the body does not run and the flow moves to the statement after the loop. For for (int i = 0; i < 5; i++) the body runs 5 times with i = 0, 1, 2, 3, 4. When i becomes 5, the condition is false. The condition is tested 6 times in all: five true, the last false.
for loop. The initialization runs once; if the condition is true, the body and the update are done and the flow returns to the condition; if false, the loop is left.Figure 3.1.16 shows the same order as a flow diagram. The operation of the loop can be summarized in six steps:
- Initialization: the loop variable takes its initial value. This step is done once.
- The condition is checked.
- If the condition is true, the body runs.
- Update: the loop variable changes.
- The flow returns to the condition; as long as the condition is true, 3–4–5 repeat.
- When the condition is false, the loop is left and execution continues with the next statement.
If the condition is false on the first check, the body never runs. The header for (int i = 10; i <= 1; i++) is valid, but its body runs zero times.
The int i declared in the header lives only inside the loop. Trying to read i after the loop gives a cannot find symbol error. If the last value of the loop variable is needed after the loop, the variable is declared before the loop and only its initial value is given in the header: int i; for (i = 1; i < 6; i++) { … }. In this case i is 6 when the loop ends, because the loop ends when i < 6 becomes false.
The update does not have to be just i++. You can go backward with i--, by twos with i += 2, or doubling with i *= 2. Table 3.1.11 gives the behavior of a few headers.
| Header | Values of i | Iterations |
|---|---|---|
for (int i = 1; i <= 5; i++) | 1, 2, 3, 4, 5 | 5 |
for (int i = 10; i >= 1; i -= 2) | 10, 8, 6, 4, 2 | 5 |
for (int i = 1; i <= 100; i *= 2) | 1, 2, 4, 8, 16, 32, 64 | 7 |
for (int i = 10; i <= 1; i++) | — | 0 |
for (int i = 1; i != 9; i += 2) | 1, 3, 5, 7 | 4 |
for (int i = 1; i != 10; i += 2) | 1, 3, 5, …, 9, 11, … | infinite |
for (int i = 0; i <= 10; i--) | 0, −1, −2, … | infinite* |
The last two rows need attention. The condition i != 10 never becomes false with odd numbers: i jumps from 9 to 11 and never sees 10. That is why < or <= is preferred to != in conditions; had i <= 10 been written, the loop would have ended after five iterations with 1, 3, 5, 7, 9. In the last row the update goes the wrong way: as i decreases, i <= 10 stays true. The starred “infinite” is meant in a practical sense. After −2,147,483,648, the smallest value of int, one more decrement wraps around to the largest value, 2,147,483,647, and the condition becomes false. The loop therefore ends after 2,147,483,649 iterations; with a body that prints to the screen that takes hours.
3.1.6.3The sum from 1 to 10
The most basic use of loops is to accumulate a value step by step. The code below finds the sum of the numbers from 1 to 10:
int sum = 0;
for (int count = 1; count <= 10; count++) {
sum += count;
}
System.out.println("Sum: " + sum);Sum: 55An accumulator is a variable that collects a result by having a value added to it in each iteration of a loop. It is initialized to 0 for a sum and to 1 for a product; these numbers are the identity elements of the operations.
sum starts at 0. The initialization step makes count 1. The condition 1 <= 10 is true and the first iteration runs: sum += count, that is, sum = sum + count, gives 0 + 1 = 1. The update makes count 2, the condition is true again, and in the second iteration sum becomes 1 + 2 = 3. This pattern repeats in the same way on every iteration (Table 3.1.12).
| Iteration | count | Condition count <= 10 | sum (after the body) |
|---|---|---|---|
| 1 | 1 | true | 0 + 1 = 1 |
| 2 | 2 | true | 1 + 2 = 3 |
| 3 | 3 | true | 3 + 3 = 6 |
| 4 | 4 | true | 6 + 4 = 10 |
| 5 | 5 | true | 10 + 5 = 15 |
| 6 | 6 | true | 15 + 6 = 21 |
| 7 | 7 | true | 21 + 7 = 28 |
| 8 | 8 | true | 28 + 8 = 36 |
| 9 | 9 | true | 36 + 9 = 45 |
| 10 | 10 | true | 45 + 10 = 55 |
| — | 11 | false | 55 (the loop ends) |
count = 2). The bold return arrow is the path from the update to the condition.The body runs exactly 10 times and the condition is tested 11 times. After the loop, sum is printed. count, however, is no longer defined: it lives only inside the loop. The result can also be checked with Gauss’s formula: the sum of the numbers from 1 to n is n(n + 1)/2, and for n = 10 it gives 55. Comparing with a known formula is an easy way to verify the bounds of a loop.
Initializing the accumulator inside the loop. If the line int sum = 0; is moved into the body, sum becomes 0 again on every iteration. More importantly, the variable now lives in the body’s block, and the println line after the loop gives a cannot find symbol error. The accumulator is always declared before the loop.
3.1.6.4Summing a range
The bounds of a loop do not have to be fixed. The program below reads two numbers from the user and adds up the integers between them:
import java.util.Scanner;
public class RangeSum {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Start value (a): ");
int a = input.nextInt();
System.out.print("End value (b): ");
int b = input.nextInt();
int sum = 0;
for (int i = a; i <= b; i++) {
sum += i;
}
System.out.println("Sum of the numbers: " + sum);
}
}When 3 and 7 are entered, the loop variable i starts from the a the user entered and 3 + 4 + 5 + 6 + 7 = 25 is computed:
Start value (a): 3
End value (b): 7
Sum of the numbers: 25If the inputs are given in reverse order, the result is surprising:
Start value (a): 7
End value (b): 3
Sum of the numbers: 0On the first check 7 <= 3 is false. The body never runs and sum stays 0. The program does not crash and gives no error message; it just gives a wrong answer. The fix is to put the two values in order before the loop. If a > b, the values of the two variables are swapped with the help of a third variable:
if (a > b) {
int temp = a;
a = b;
b = temp;
}When this block is added before the line int sum = 0;, the input 7 and 3 gives 25 as well. To swap the variables, writing a = b; b = a; is not enough: after the first assignment the old value of a is lost and both variables are 3. The variable temp is there to save this value.
3.1.7while and do-while
3.1.7.1The while loop
A while loop is a loop that tests the condition before every iteration and repeats the body as long as the condition is true. Its header contains only the condition.
int i = 0;
while (i < 5) {
// statements in the loop
i++;
}while tests only the condition. The initialization is written before the loop and the update separately inside the body. Because the condition is tested before the body, the body may never run. When the number of iterations is not known in advance, while is the natural choice: “read until the user enters 0,” “drop the last digit until the number is 0,” “retry until no error is left.”
while flow diagram; right, do-while. In while the condition is in front of the body, in do-while behind it; in both loops the body does the update itself.Because the update is left to the programmer, the biggest danger of while is the infinite loop. If i++ is forgotten in the code above, i stays 0, 0 < 5 is always true, and the program never ends. The compiler does not catch this, because some programs are deliberately written with an infinite loop: the main loop of a server or an embedded system must never end.
for and while can be converted into each other. The sum from 1 to 10 can be written in either form:
int sum = 0;
int count = 1;
while (count <= 10) {
sum += count;
count++;
}
System.out.println("Sum: " + sum);Sum: 55Both loops have the same three parts: initialization count = 1, condition count <= 10, update count++. for gathers them on one line; in while the parts are scattered and the update can be forgotten. There is one more small difference between the two versions: in the while version, count is declared before the loop, so it can also be read after the loop, and its value is 11.
3.1.7.2Factorial
The factorial of a positive integer is the product of all the integers from 1 to that number: 5! = 1 × 2 × 3 × 4 × 5 = 120. By definition 0! = 1. Written with while, it looks like this:
int n = 5;
int factorial = 1;
int count = 1;
while (count <= n) {
factorial *= count;
count++;
}
System.out.println(n + " factorial: " + factorial);5 factorial: 120The starting value of the product is 1. If it started at 0, every multiplication would give 0 and the result would always be 0. Table 3.1.13 shows each iteration of the loop.
| Iteration | Condition | factorial *= count | count (after the iteration) |
|---|---|---|---|
| 1 | 1 <= 5 true | 1 × 1 = 1 | 2 |
| 2 | 2 <= 5 true | 1 × 2 = 2 | 3 |
| 3 | 3 <= 5 true | 2 × 3 = 6 | 4 |
| 4 | 4 <= 5 true | 6 × 4 = 24 | 5 |
| 5 | 5 <= 5 true | 24 × 5 = 120 | 6 |
| — | 6 <= 5 false | 120 (the loop ends) | 6 |
The factorial grows very fast and soon exceeds the limit of int. An int holds at most 2,147,483,647; 12! = 479,001,600 fits, and 13! = 6,227,020,800 does not. With n = 13 the same code prints 1932053504. Java raises no error on integer overflow; the result is silently wrong. With long the results are correct up to 20!; 21! overflows long too.
3.1.7.3Exponentiation
An integer power of a base is also computed by accumulating a product: 34 = 3 × 3 × 3 × 3 = 81. Because the number of iterations (the exponent) is known, for is appropriate:
import java.util.Scanner;
public class Power {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter base and exponent: ");
int base = sc.nextInt();
int exp = sc.nextInt();
long result = 1;
for (int i = 1; i <= exp; i++) {
result = result * base;
}
System.out.println("Result: " + result);
System.out.println("Math.pow: " + Math.pow(base, exp));
sc.close();
}
}Enter base and exponent: 3 4
Result: 81
Math.pow: 81.0result starts at 1 and the loop multiplies by base exp times. If exp = 0, the loop never runs and the result is correctly 1. result is chosen as long to guard against overflow: 231 does not fit in an int but does fit in a long. long has a limit too; with the input 2 63 the program prints Result: -9223372036854775808.
Java’s ready-made Math.pow(base, exp) method does the same job but returns the result as a double. That is why 81.0 is printed, not 81. Our own loop shows how the algorithm works. In real programs ready-made methods are preferred: they are well tested and also cover cases a loop cannot, such as fractional exponents.
3.1.7.4The do-while loop
A do-while loop is a loop that runs the body first and then tests the condition. The body runs at least once, independent of the condition.
int i = 0;
do {
// statements in the loop
i++;
} while (i < 5);do-while repeats as long as the condition holds; its only difference is that it tests the condition at the end of the iteration. There is one detail in the writing: the semicolon after while (condition) is required. If it is forgotten, the compiler gives a ';' expected error. In a while loop, by contrast, that semicolon is a mistake and can produce an insidious infinite loop.
3.1.7.5Input validation
The typical use of do-while is to repeat a question until a valid value is obtained from the user. The question must be asked at least once; that is exactly what do-while does.
import java.util.Scanner;
public class DoWhileInput {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num;
do {
System.out.print("Enter a number (1-10): ");
num = input.nextInt();
} while (num < 1 || num > 10);
System.out.println("Accepted number: " + num);
}
}Suppose the user types 15, 0, and 7 in turn:
Enter a number (1-10): 15
Enter a number (1-10): 0
Enter a number (1-10): 7
Accepted number: 715 and 0 are outside the range: the condition num < 1 || num > 10 is true and the question is asked again. 7 is valid: the condition is false and the loop is left. num is declared before the loop because it is used both in the condition and after the loop. Had it been declared inside the body, the line while (num < 1 …) could not see it and would give a cannot find symbol error: the condition is outside the body’s block.
Table 3.1.14 traces the same code with the inputs 12, −3, and 4. The short-circuiting of || in the condition can be seen here as well.
| Iteration | num read | num < 1 | num > 10 | Condition | Result |
|---|---|---|---|---|---|
| 1 | 12 | false | true | true | the question is repeated |
| 2 | −3 | true | not tested | true | the question is repeated |
| 3 | 4 | false | false | false | the loop is left |
-3 < 1 is true, || does not look at the right side and the question is asked again.The question is asked three times in all and “Accepted number: 4” is printed. The loop goes on until a valid number arrives. If the user types text such as “ten” instead of a number, nextInt() throws InputMismatchException. To handle that case too, hasNextInt() can be used to check first whether the input is a number.
The difference between while and do-while appears when the condition is false on the first attempt:
int i = 10;
while (i < 5) {
System.out.println("while: " + i);
i++;
}
int j = 10;
do {
System.out.println("do-while: " + j);
j++;
} while (j < 5);
System.out.println("i = " + i + ", j = " + j);do-while: 10
i = 10, j = 11With i = 10, while tests the condition first: 10 < 5 is false and the body never runs; i stays 10. With j = 10, the do block is entered without looking at the condition. “do-while: 10” is printed and j becomes 11. Only now is the condition tested: 11 < 5 is false and the loop is left. The same condition, a different result: while ran 0 iterations and do-while ran 1.
A real consequence of this difference appears in counting digits. The loop while (num > 0) { digits++; num /= 10; }, which counts the digits of a number, gives 4 for 2024 (2024 → 202 → 20 → 2 → 0), but 0 for 0: the condition is false on the first attempt. Yet 0 is a one-digit number. When the loop is converted to do-while, the body runs at least once and 1 is found for 0:
int num = 0, digits = 0;
do {
digits++;
num /= 10;
} while (num != 0);
System.out.println(digits);The condition is written here as num != 0. That way negative numbers are counted correctly too: 2 is found for −45. With while (num > 0) the loop never runs for negative numbers.
3.1.7.6Comparing the three loops
for | while | do-while | |
|---|---|---|---|
| When is the condition tested? | Before every iteration | Before every iteration | After every iteration |
| Minimum iterations? | 0 | 0 | 1 |
| Initialization / update | In the header, on one line | Outside the loop / in the body | Outside the loop / in the body |
| When to use? | The number of iterations is known: “1 to n,” “every element of the array” | Until a condition changes: “until the number is 0” | The task must be done at least once: input validation, a menu |
| Syntax | for (init; condition; update) { } | while (condition) { } | do { } while (condition); |
The three loops can be converted into one another; the choice is made by readability. If a loop advances with a counter, for is written: someone reading the header can see how many times the loop will run. If the end of the loop depends on an event, while is clearer. If the body must run at least once, do-while is chosen.
3.1.7.7Infinite loops and boundary errors
Most loop errors fall into two groups: loops that never end, and loops that run one iteration too many or too few. The compiler catches neither group.
An infinite loop is a loop whose condition never becomes false. The most common causes are: forgetting the update in while, making the update in the wrong direction (i-- with i <= 10), and a != condition that skips over the target value. A more insidious cause is a semicolon placed after the loop header:
int i = 0;
while (i < 5); {
i++;
}The semicolon sets up a loop with an empty body. i never increases, 0 < 5 is always true, and the program silently freezes. The block below does not belong to the loop; the flow never reaches it. If the same mistake is made in a for header, no infinite loop results but the logic is still broken: for (int i = 0; i < 3; i++); { System.out.println("hello"); } runs the empty body three times and prints “hello” only once.
An off-by-one error is a mistake, usually in the starting value or in the comparison operator of the condition, that makes a loop run one iteration too many or one too few.
For “1 to 10,” writing i < 10 skips 10 and runs 9 iterations. With i = 0 and i <= 10, it runs 11 iterations. These mistakes are easy to find by tracing by hand: the value of the loop variable on the first iteration and its value on the last are checked separately. How many iterations a loop runs can also be computed with the formula end − start + 1 (with <=, in steps of one). A typical example is a pattern in which every line is “+-” repeated 10 times. The line is 20 characters; if the inner loop starts at j = 0 and runs with j < 21, 21 characters are printed and the line ends with an extra “+.”
Keeping a counter with floating-point numbers is also a source of boundary errors. The loop for (double x = 0; x != 1.0; x += 0.1) never ends: adding 0.1 ten times gives not exactly 1.0 but 0.9999999999999999, and x skips over 1.0. Loop counters should always be integers; if a decimal value is needed, it is computed from the counter in the body: double x = i * 0.1;.
3.1.8Nested loops
A nested loop is a loop inside the body of another loop. The outer loop is called the outer loop and the one in the body the inner loop.
Nested loops are used when working with two-dimensional structures: tables, matrices, patterns drawn on the screen, the pixels of an image. The analogy is a clock. Each time the hour hand (the outer loop) moves one step, the minute hand (the inner loop) makes a full turn. The hour hand does not move until the minute hand has finished its turn.
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 2; j++) {
// nested loop body
}
}On every iteration of the outer loop the inner loop starts over and runs to its end. The total number of times the body runs is therefore the product of the iteration counts of the two loops: outer 3 iterations × inner 2 iterations = 6 times (Figure 3.1.20).
The product rule also shows the cost of nested loops. Two loops of 1,000 iterations each run the body 1,000,000 times, and three loops 1,000,000,000 times. A billion operations can take a few seconds on today’s computer. As the number of nested loops grows, the code becomes both more complicated and slower. How many nested loops a problem needs is the main factor that determines the speed of the algorithm.
3.1.8.1How a nested loop works
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 2; j++) {
System.out.println("i = " + i + ", j = " + j);
}
}The flow goes step by step as follows. The outer loop starts: i = 1, 1 <= 3 is true. The inner loop starts: j = 1 and the body prints “i = 1, j = 1.” With j++, j becomes 2 and “i = 1, j = 2” is printed. When j becomes 3, 3 <= 2 is false and the inner loop is complete. The flow returns to the outer loop: with i++, i becomes 2, the condition is true, and the inner loop starts again from j = 1. This continues until the i = 3 iteration is finished too. Finally i becomes 4, 4 <= 3 is false, and the outer loop ends as well.
| Step | i | j | Event | Screen |
|---|---|---|---|---|
| 1 | 1 | 1 | the inner loop starts | i = 1, j = 1 |
| 2 | 1 | 2 | i = 1, j = 2 | |
| 3 | 1 → 2 | 3 | 3 <= 2 false: the inner loop ends, i++ | |
| 4 | 2 | 1 | the inner loop starts again | i = 2, j = 1 |
| 5 | 2 | 2 | i = 2, j = 2 | |
| 6 | 2 → 3 | 3 | the inner loop ends, i++ | |
| 7 | 3 | 1 | the inner loop starts again | i = 3, j = 1 |
| 8 | 3 | 2 | i = 3, j = 2 | |
| 9 | 3 → 4 | 3 | the inner loop ends; 4 <= 3 false: the outer loop ends |
The body runs 3 × 2 = 6 times. The outer condition is tested 4 times and the inner condition 3 × 3 = 9 times: each time the inner loop starts it makes two true tests and one false test. In the output you can see that i changes slowly and j quickly: while i is 1, j goes over the values 1 and 2.
3.1.8.2A star pattern
The bound of the inner loop does not always have to be fixed. If the bound is tied to the outer loop’s variable, a different number of iterations is made on each row:
for (int i = 1; i <= 4; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("* ");
}
System.out.println();
}*
* *
* * *
* * * * The condition of the inner loop is j <= i. In the first row i = 1, so the inner loop runs once; in the second row twice, in the third three times, and in the fourth four times. print("* ") does not move to a new line; the stars line up side by side. When the inner loop ends, println() moves to the next line. This line is outside the inner loop and inside the outer loop: it runs once at the end of each row.
i, the cells j = 1 … i are filled.The total number of stars is 1 + 2 + 3 + 4 = 10. In general, a triangle of n rows prints n(n + 1)/2 stars. This number is the typical cost of loops whose inner bound depends on the outer one: about half of the n2 of a rectangular grid. If the inner loop started at j = i and ran to 4, the iteration counts would be 4, 3, 2, 1 and the total would again be 10; this time the pattern would be an inverted triangle.
Putting println() at the wrong level. If it is written inside the inner loop, a new line follows every star and a single column of ten lines results. If it is written outside the outer loop, all the stars line up on a single line. Which line belongs to which loop is determined only by braces; keeping the indentation tidy makes this relationship visible.
3.1.8.3Place value
for (int tens = 0; tens <= 4; tens++) {
for (int ones = 1; ones <= 9; ones++) {
int num = tens * 10 + ones;
System.out.println("Tens digit: " + tens
+ ", ones digit: " + ones + " --> " + num);
}
}This code builds two-digit numbers from a tens digit and a ones digit. To find how many lines it prints, the iteration counts of the two loops are multiplied. The outer loop runs 5 iterations for tens = 0 … 4 and the inner loop 9 iterations for ones = 1 … 9: 5 × 9 = 45 lines. The first and last lines are:
Tens digit: 0, ones digit: 1 --> 1
Tens digit: 0, ones digit: 2 --> 2
Tens digit: 0, ones digit: 3 --> 3
…
Tens digit: 4, ones digit: 8 --> 48
Tens digit: 4, ones digit: 9 --> 49num = tens * 10 + ones takes values from 1 to 49. Because ones does not start at 0, 10, 20, 30, and 40 are never printed; 0 is not printed either. There are 49 numbers from 1 to 49, and since 4 of them are skipped, 45 lines remain. The two computations confirm each other.
The print line of the code is split over two lines. In Java a long string can be broken into pieces with + and continued on the next line. Text inside quotation marks, however, cannot be cut at the end of a line. Writing "Tens digit: and ending the line gives an unclosed string literal error.
3.1.8.4The multiplication table
for (int i = 1; i <= 10; i++) {
for (int j = 1; j <= 10; j++) {
int product = i * j;
System.out.print(i + "x" + j + "=" + product + "\t");
}
System.out.println(); // new line
}The outer loop goes over the rows (i) and the inner loop over the columns (j): 10 × 10 = 100 products. print does not move to a new line; the "\t" added after each product is a tab character, which aligns the columns to the next tab stop. When the row is finished, println() moves to the next line.
i = 2 iteration: the inner loop goes over the columns with j = 1, 2, 3, 4 ….1x1=1 1x2=2 1x3=3 1x4=4 1x5=5 1x6=6 …
2x1=2 2x2=4 2x3=6 2x4=8 2x5=10 2x6=12 …
3x1=3 3x2=6 3x3=9 3x4=12 3x5=15 3x6=18 …
…
10x1=10 10x2=20 10x3=30 10x4=40 10x5=50 …Tab stops are usually 8 characters apart. A cell of 9 characters such as “10x10=100” overshoots a stop and can shift the rest of the row. For a tidier table, fixed-width fields are used with printf: System.out.printf("%4d", i * j); writes each number right-aligned in a field of 4 characters. %-4d left-aligns, and %04d fills missing digits with 0.
3.1.9break and continue
Loops normally end when the condition becomes false. Sometimes a decision has to be made in the middle of a loop: if the thing being sought has been found, the remaining iterations are pointless; if an item is useless, that iteration should be skipped. Java offers two statements for these two jobs.
break ends the nearest enclosing loop (or switch) at once; the flow moves to the statement after the loop. continue skips the rest of the current iteration and moves to the next one; in for, the update runs first and then the condition.
3.1.9.1break in loops
for (int i = 1; i <= 10; i++) {
if (i == 5) {
break;
}
System.out.println("Loop step: " + i);
}
System.out.println("Left the loop.");Loop step: 1
Loop step: 2
Loop step: 3
Loop step: 4
Left the loop.For i = 1, 2, 3, and 4, i == 5 is false; break is skipped and the step is printed. At i = 5 the condition is true and break runs. The loop ends at that moment: 5 is not printed, and 6–10 are never tried. The flow moves to the line after the loop and “Left the loop.” is printed.
break: 1–4 are printed, the loop stops at 5, and 6–10 are never processed. Bottom, continue: the odd numbers are printed and the even numbers skipped, but the loop goes on to 10.A statement written right after break in the same block can never be reached. Java treats this as a compile-time error: the code for (…) { break; System.out.println(i); } gives error: unreachable statement. That is why break is almost always used inside an if.
3.1.9.2Prime numbers: a flag and break
Finding out whether a number is prime is the best-known use of break. A prime number is an integer greater than 1 that is divisible only by 1 and itself. The program looks for a divisor starting from 2; the moment it finds the first divisor, it stops the search.
import java.util.Scanner;
public class PrimeCheck {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = sc.nextInt();
boolean isPrime = true; // flag
if (num < 2) isPrime = false; // 0 and 1 are not prime
for (int divisor = 2; divisor <= num / 2; divisor++) {
if (num % divisor == 0) { // divides evenly
isPrime = false;
break; // break out of the loop
}
}
if (isPrime) {
System.out.println(num + " is prime.");
} else {
System.out.println(num + " is not prime.");
}
sc.close();
}
}Enter a number: 21
21 is not prime.
Enter a number: 97
97 is prime.isPrime is a flag: a boolean variable that carries whether a condition has occurred during the loop. At first the number is assumed to be prime. Since 0 and 1 are not prime, the flag is lowered at once when num < 2. The loop tries the divisors from 2 to num / 2. If an exact divisor is found, the flag is lowered and the loop is left with break. After the loop the flag is examined and the result is printed.
num | Divisors tried | Attempts | isPrime |
|---|---|---|---|
| 21 | 2 (remainder 1), 3 (remainder 0) → break | 2 | false |
| 97 | 2, 3, …, 48; none divides | 47 | true |
| 91 | 2, 3, 4, 5, 6, 7 (remainder 0) → break | 6 | false |
| 2 | none (2 <= 1 false) | 0 | true |
| 1 | none; the flag is lowered by num < 2 | 0 | false |
97 is prime, and the program finds this out only after 47 attempts. There is a faster way. If a number has a divisor other than 1 and itself, one of those divisors is less than or equal to the square root of the number. This is because if num = a × b, a and b cannot both be greater than √num; their product would exceed num. The loop condition is changed accordingly:
for (int divisor = 2; divisor * divisor <= num; divisor++) {
if (num % divisor == 0) {
isPrime = false;
break;
}
}The condition divisor * divisor <= num applies the square-root bound without calling Math.sqrt and without carrying floating-point error. For 97, √97 ≈ 9.85; the divisors 2 … 9 are tried, and only 8 attempts are made instead of 47. For a seven-digit prime such as 1,000,003 the difference is much greater: 500,000 attempts with the num / 2 bound and 999 with the square-root bound.
3.1.9.3continue in loops
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
continue;
}
System.out.println("Odd number: " + i);
}Odd number: 1
Odd number: 3
Odd number: 5
Odd number: 7
Odd number: 9i = 1 is odd, the condition is false, and the number is printed. i = 2 is even: continue runs, the rest of the body, that is, the print line, is skipped, and the flow goes directly to i++. This continues up to 10. When i = 11, 11 <= 10 is false and the loop ends normally. continue does not end the loop; it only cuts that iteration short. The same job can also be written without continue by reversing the condition: if (i % 2 != 0) System.out.println(…);. continue flattens the code when the cases to be skipped are to be filtered out at the start of the body, that is, when the body is long.
break: when i == 5 the flow leaves the loop completely. Right, continue: when i is even the print is skipped and the flow goes to the update (i++); the loop goes on.continue has a hidden danger in a while loop. In for, the update is in the header and runs after continue as well. In while, the update is inside the body, and continue can skip it too:
int i = 0;
while (i < 5) {
if (i == 2) {
continue;
}
System.out.print(i + " ");
i++;
}
System.out.println("done");This code prints “0 1 ” and then loops forever. When i becomes 2, continue skips the rest of the body, including i++. i stays 2, the condition is always true, and “done” is never printed. If the loop is converted to the form for (int i = 0; i < 5; i++), the update moves to the header and the output is “0 1 3 4 done.”
3.1.9.4break and labels in nested loops
break ends only the nearest loop it is in. A break in the inner loop does not touch the outer loop:
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
if (j == 2) {
break;
}
System.out.println(i + " " + j);
}
}1 1
2 1
3 1For each i the inner loop prints j = 1 and ends with break at j = 2. The outer loop goes on and starts the inner loop again with the next i. In the end only j = 1 is printed for each i.
If both loops have to be left at once, Java offers the labeled break. A name and a colon are written in front of the outer loop; break is used with that name:
outer:
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
if (i * j == 4) {
break outer;
}
System.out.println(i + " x " + j);
}
}
System.out.println("done");1 x 1
1 x 2
1 x 3
2 x 1
doneThe label outer: names the outer loop. In the i = 1 iteration the three products (1, 2, 3) are not equal to 4 and all are printed. The inner loop ends and the outer loop moves to i = 2. 2 × 1 = 2 is printed. At i = 2, j = 2, 2 × 2 = 4 and the condition is true. break outer; leaves not only the inner loop but the labeled outer loop as well. The remaining cells (2 × 3 and the whole i = 3 iteration) are never visited. The flow jumps past both loops and “done” is printed.
break. The green cells have been printed; at the 2 × 2 cell the condition came out true and break outer left both loops at once. The dashed cells were never visited.With an unlabeled break, only the inner loop would be left and the i = 3 iteration would run too. The products in that iteration are 3, 6, and 9; none equals 4, so all three are printed. The output would be seven lines: 1 x 1, 1 x 2, 1 x 3, 2 x 1, 3 x 1, 3 x 2, 3 x 3, followed by “done.” continue can also be used with a label. continue outer; abandons the rest of the inner loop and moves to the next iteration of the outer loop:
outer:
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
if (j == 2) {
continue outer;
}
System.out.println(i + " " + j);
}
}1 1
2 1
3 1Labels are rarely used. Because they carry the flow several levels away, they make the code harder to follow. A more common way of leaving two loops is to move the nested loop into a separate method and return from the method with return when the sought value is found. In Java goto is a reserved word but cannot be used; the labeled break and continue are the only forms of “jumping” the language allows.
3.1.10Common mistakes
Some of the mistakes in control structures are caught by the compiler, and its message points to the place. Others compile, run, and merely give a wrong result. The second group is more dangerous, because nothing warns the programmer. Table 3.1.18 collects the typical mistakes in decision structures and Table 3.1.19 those in loops. The compiler messages were obtained with JDK 21.
| Mistake | Example | Result | Correct form |
|---|---|---|---|
Comparing with = | if (x = 5) | incompatible types: int cannot be converted to boolean | if (x == 5) |
Semicolon after if | if (x > 5); { … } | Compiles; the block always runs | Delete the semicolon |
| Block without braces | if (k) a(); b(); else c(); | 'else' without 'if' | { } for several statements |
Block without braces, no else | if (k) a(); b(); | Compiles; b() always runs | if (k) { a(); b(); } |
| Writing a range as in mathematics | 60 <= grade < 90 | bad operand types for binary operator '<' | grade >= 60 && grade < 90 |
| Wrong order in a chain | if (grade >= 60) … else if (grade >= 90) … | Compiles; the 90 branch is never reached | Arrange thresholds from largest to smallest |
Forgetting break | case 2: … case 3: … | Compiles; the case labels below run too | End every case with break |
Assignment without default | The variable is assigned only in the case labels | variable season might not have been initialized | Add default |
A variable as a case label | int b = 2; … case b: | constant expression required | A constant or a final variable |
| A period in decimal input | -7.5 for nextDouble() in the Turkish locale | InputMismatchException | Type -7,5 or use useLocale |
| Mistake | Example | Result | Correct form |
|---|---|---|---|
| Forgetting the update | while (i < 5) { println(i); } | Infinite loop; the compiler does not catch it | i++ in the body |
| Updating in the wrong direction | for (int i = 0; i <= 10; i--) | Practically an infinite loop | i++ |
| A semicolon after the loop header | while (i < 5); { i++; } | An infinite loop with an empty body | Delete the semicolon |
| Off-by-one error | i < 10 for “1 to 10” | Compiles; runs 9 iterations | i <= 10; check the first and last iteration |
| Using the loop variable outside | for (int i …) { } then println(i) | cannot find symbol | Declare i before the loop |
Code after break | break; System.out.println(i); | unreachable statement | Move the line before break |
| Wrong starting value | int factorial = 0; | Compiles; the result is always 0 | A sum starts at 0, a product at 1 |
| Resetting the accumulator in the loop | int sum = 0; in the body | Reset on every iteration; not accessible outside the loop | Declare it before the loop |
continue in while | if (i == 2) continue; followed by i++ | Infinite loop | Use for, or do i++ first |
No semicolon at the end of do-while | } while (i < 3) | ';' expected | } while (i < 3); |
int overflow | 13! with int | Compiles; prints 1932053504 | long |
The most reliable way to find mistakes that compile is to trace by hand. The code is run on paper with a few small inputs, writing the variables into a table after each iteration. Three inputs in particular should be tried: the case in which the loop should not run at all (e.g. n = 0), the case in which it should run once, and a boundary value. A trace table showing the variables after each iteration reveals boundary errors without running the code.
3.1.11Summary
- Three basic structures: sequential execution, decisions, and loops. Every algorithm can be written by combining them. In sequential code each line depends on the state left by the previous lines.
- Condition: a
booleanexpression whose result istrueorfalse.=is assignment and==is comparison; Java does not compileif (x = 7). if/else: if the condition is true one block runs, otherwise the other; at most one of the two blocks runs. Without braces only the first statement is attached to theif; indentation means nothing.- The
else ifchain: conditions are tried from top to bottom, the block of the first true condition runs, and the chain ends. The order of the conditions takes the place of upper bounds. - Nested decisions: the inner condition is tested only if the outer condition is true. An
elseattaches to the nearestifthat has noelseyet. Deep structures are flattened with&&. - Short-circuiting:
&&does not evaluate the right side if the left isfalse, and||does not if the left istrue.b != 0 && a / b > 2is safe; operations with side effects are not written on the right.?:is an expression that chooses one of two values. switch: compares a value with constantcaselabels. Acaseis an entry point; withoutbreakthe flow falls into thecaselabels below. The selector can bebyte,short,char,int, their wrappers,String, orenum; labels are constant and unique.- The
switchexpression (Java 14+): the formcase 3, 4, 5 -> …; there is no fall-through, it produces a value, and it must cover all possibilities (defaultis required forint). for: initialization, condition, and update on one line; the order of execution is initialization, then on every iteration condition → body → update. A variable declared in the header lives only in the loop.whileanddo-while:whiletests the condition first and may run 0 iterations;do-whiletests afterwards, runs at least 1 iteration, and needs a;at the end. Input validation is the typical use ofdo-while.- Accumulator: a sum starts at 0, a product at 1, and it is declared before the loop.
intis enough up to 12!, andlongup to 20!; overflow is silent. - Nested loops: the inner loop starts over on every iteration of the outer loop; the body runs as many times as the product of the iteration counts. If the inner bound depends on the outer (
j <= i), the total is n(n + 1)/2. breakandcontinue:breakends the nearest loop, andcontinueskips the rest of the iteration. The labeledbreak outer;leaves the named outer loop too. A flag andbreakare used together in the prime-number search; the bound is shortened withdivisor * divisor <= num.- Mistakes: infinite loops, off-by-one errors, a wrong order of conditions, and a forgotten
breakcompile but run wrongly; they are found by tracing by hand.
3.1.12Key terms
- control structure
- condition
- block
- if statement
- else-if chain
- nested decision
- short-circuit evaluation
- conditional operator
- switch statement
- fall-through
- switch expression
- loop
- for loop
- while loop
- do-while loop
- accumulator
- nested loop
- break / continue
- iteration
- infinite loop
- off-by-one error
- flag
- labeled break
3.1.13Test Yourself
What does the chain below print for
temp= 18, 15, 0, and −3?if (temp < 0) System.out.println("freezing"); else if (temp < 15) System.out.println("cold"); else if (temp < 25) System.out.println("mild"); else System.out.println("hot");Answer
18: mild; 15: mild; 0: cold; −3: freezing. In a chain written with
<, the thresholds go from smallest to largest. 15 passes the “cold” link because15 < 15is false, and falls to “mild.” 0 does not give “freezing” either, because0 < 0is false.The line
boolean s = (a != 0) && (b / a > 1) || b > 3;is run withint a = 0, b = 5;. Does the program give a division-by-zero error? What iss?Answer
It does not;
s = true.&&comes before||; the expression reads((a != 0) && (b / a > 1)) || (b > 3). Becausea != 0is false,b / ais never evaluated, thanks to short-circuiting, and the parenthesized part isfalse. Thenb > 3comes out true and the result istrue.What value does the following
switchgivetfork= 3, 1, 5, and 7?int t = 0; switch (k) { case 1: t += 1; case 3: t += 3; case 5: t += 5; break; default: t += 100; }Cevap
k = 3: 3 + 5 = 8.k = 1: 1 + 3 + 5 = 9.k = 5: 5.k = 7: 100. Because the first twocaselabels have nobreak, the flow falls through tocase 5; thebreakincase 5prevents the move intodefault.How many iterations does the loop
int i; for (i = 3; i <= 30; i += 4) { … }run? Which values ofidoes the body see? What isiafter the loop?Answer
7 iterations: 3, 7, 11, 15, 19, 23, 27. The next value is 31 and
31 <= 30is false; after the loopi = 31. The number of iterations can also be computed as ⌊(30 − 3) / 4⌋ + 1 = 6 + 1 = 7.After the code
int n = 100, steps = 0; while (n > 1) { n /= 2; steps++; }, what arestepsandn?Answer
steps = 6,n = 1.n: 100 → 50 → 25 → 12 → 6 → 3 → 1. Integer division discards the fraction: 25 / 2 = 12, 3 / 2 = 1. The loop finds the number of halvings needed to bring the number down to 1, that is, ⌊log2 100⌋ = 6.After the code
int x = 0; do { x += 3; } while (x < 0);andint y = 0; while (y < 0) { y += 3; }, what arexandy?Answer
x = 3,y = 0. The condition is false on the first test in both loops.do-whileruns the body once without looking at the condition;whiletests the condition first and never enters the body.How many times does the body run in the code below, and what is
count?int count = 0; for (int i = 1; i <= 5; i++) for (int j = 1; j <= i; j++) if ((i + j) % 2 == 0) count++;Cevap
The body runs 1 + 2 + 3 + 4 + 5 = 15 times. The pairs whose sum is even number 1, 1, 2, 2, 3 for
i= 1 … 5 respectively:count = 9. For example, ati = 5the sums forj= 1, 3, 5 are 6, 8, 10.What does the following code print?
int s = 0; for (int i = 1; i <= 10; i++) { if (i % 4 == 0) continue; if (i > 7) break; s += i; } System.out.println(s);Cevap
24. 1, 2, 3 are added (6). 4 is skipped by
continue. 5, 6, 7 are added (24). 8, being divisible by 4, is again skipped bycontinue; it does not reach thebreakline. At 9,9 > 7is true andbreakends the loop; 9 and 10 are not added.Which of these compile? (a)
switch (3.0) { default: }(b)final int K = 2; switch (x) { case K: break; }(c)if (x = 0) { }(d)while (true) { } System.out.println();Answer
Only (b). (a)
selector type double is not allowed. (b)Kis afinalvariable with a constant value and can be a label. (c)incompatible types: int cannot be converted to boolean. (d) Because there is nobreakinside thewhile (true)loop, it never ends, and anunreachable statementerror is given for the next line.
3.1.14Further reading
- Oracle, The Java Tutorials, “Control Flow Statements”: a short, official account with examples of
if,switch, loops, andbreak/continue; there is also a separate “Switch Expressions” page for switch expressions. - A. B. Downey and C. Mayfield, Think Java (2nd ed., 2019), Chapters 5–6: conditions, logical operators, and loops are treated in plain language with many short exercises. The book can be read free online.
- J. Gosling et al., The Java Language Specification, Java SE 21 Edition, Chapter 14: the exact rule for every statement, fall-through, labels, and the full definition of the “unreachable statement” check are here.
- C. S. Horstmann, Core Java, Volume I: Fundamentals (12th ed.), Section 3.8: explains control flow by comparison with C/C++; a short reference for the experienced reader.
3.1.15References
- C. Böhm, G. Jacopini, “Flow Diagrams, Turing Machines and Languages with Only Two Formation Rules”, Communications of the ACM, 9(5), 366–371, 1966.
- P. Deitel, H. Deitel, Java: How to Program (Early Objects), 11th ed., Pearson, 2017 (Chapters 4–5: Control Statements).
- A. B. Downey, C. Mayfield, Think Java, 2nd ed., O’Reilly, 2019 (Chapter 5: Conditionals and Logic; Chapter 6: Loops).
- J. Gosling, B. Joy, G. Steele, G. Bracha, A. Buckley, D. Smith, G. Bierman, The Java Language Specification, Java SE 21 Edition, Oracle, 2023 (Chapter 14: Blocks, Statements, and Patterns).
- C. S. Horstmann, Core Java, Volume I: Fundamentals, 12th ed., Pearson, 2022 (3.8: Control Flow).
- Oracle, The Java Tutorials: Control Flow Statements, docs.oracle.com/javase/tutorial/java/nutsandbolts/flow.html.
- K. Sierra, B. Bates, T. Gee, Head First Java, 3rd ed., O’Reilly, 2022.
Related pages: Chapter 3.1 slides · Study questions · Glossary · © Sercan Külcü. All rights reserved.