Chapter 7
Going Around in Circles (or, Using Loops)
IN THIS CHAPTER
The thrill of while loops
The splendor of do loops
The wonder of for loops
In this chapter, you find out how to write programs that hang around by using loops, which let them execute the same statements more than once.
Loops are the key to writing one of the most common types of programs: programs that get input from the user, do something with it, get more input from the user and do something with that, and keep going this way until the user has had enough.
Put another way, loops are like the instructions on your shampoo: Lather. Rinse. Repeat.
Using Your Basic while Loop
The most basic of all looping statements in Java is while. The while statement creates a type of loop that’s called a while loop, which is simply a loop that executes continuously as long as some conditional expression evaluates to true. while loops are useful in all sorts of programming situations, so you use while loops a lot. (We tell you about other kinds of loops later in this chapter.)
The while statement
The basic format of the while statement is this:
while (expression)statement
The while statement begins by evaluating the expression. ...
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.
Read now
Unlock full access