Chapter 6. Loops and Strings

Computers are often used to automate repetitive tasks, such as searching for text in documents. Repeating tasks without making errors is something that computers do well and people do poorly.

In this chapter, you’ll learn how to use while and for loops to add repetition to your code. We’ll also take a first look at String methods and solve some interesting problems.

The while Statement

Using a while statement, we can repeat the same code multiple times:

int n = 3;
while (n > 0) {
    System.out.println(n);
    n = n - 1;
}
System.out.println("Blastoff!");

Reading the code in English sounds like this: “Start with n set to 3. While n is greater than 0, print the value of n, and reduce the value of n by 1. When you get to 0, print Blastoff! So the output is as follows:

3
2
1
Blastoff!

The flow of execution for a while statement is shown here:

  1. Evaluate the condition in parentheses, yielding true or false.

  2. If the condition is false, skip the following statements in braces.

  3. If the condition is true, execute the statements and go back to step 1.

This type of flow is called a loop, because the last step “loops back around” to the first. Figure 6-1 shows this idea using a flowchart.

Figure 6-1. Flow of execution for a while loop

The body of the loop should change the value of one or more variables so that, eventually, the condition becomes false and the loop terminates. Otherwise, ...

Get Think Java, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.