Skip to Content
Think Java, 2nd Edition
book

Think Java, 2nd Edition

by Allen B. Downey, Chris Mayfield
November 2019
Beginner
326 pages
6h 44m
English
O'Reilly Media, Inc.
Book available
Content preview from Think Java, 2nd Edition

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, ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Head First Java, 2nd Edition

Head First Java, 2nd Edition

Kathy Sierra, Bert Bates
Java in a Nutshell, 8th Edition

Java in a Nutshell, 8th Edition

Benjamin J. Evans, Jason Clark, David Flanagan
Java in a Nutshell, 7th Edition

Java in a Nutshell, 7th Edition

Benjamin J. Evans, David Flanagan
The Well-Grounded Java Developer, Second Edition

The Well-Grounded Java Developer, Second Edition

Benjamin Evans, Martijn Verburg, Jason Clark

Publisher Resources

ISBN: 9781492072492Errata PageSupplemental Content