The while Loop

Another of Java’s loops is the while. The general form of the while loop is

while(condition) statement;

where statement may be a single statement or a block of statements, and condition defines the condition that controls the loop. The condition may be any valid Boolean expression. The loop repeats while the condition is true. When the condition becomes false, program control passes to the line immediately following the loop.

Here is a simple example in which a while is used to print the alphabet:

Image

Here, ch is initialized to the letter a. Each time through the loop, ch is output and then incremented. This process continues until ...

Get Java, A Beginner's Guide, 5th Edition, 5th 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.