Loops
In addition to being able to apply conditions to your programs and see different outcomes based on various if/then scenarios, you sometimes want your code just to do the same thing over and over again until the job is done. In this section, learn about two constructs used to iterate over code or execute it more than once: for loops and while loops.
A loop is a programming construct that executes repeatedly while some condition (or set of conditions) is met. For instance, you might ask a program to read all records until the end of a file, or loop over all the elements of an array, processing each one. (You'll learn about arrays in this tutorial's Java Collections section.)
The basic loop construct in the Java language is the for statement, which lets you iterate over a range of values to determine how many times to execute a loop. The abstract syntax for a for loop is:
for (initialization; loopWhileTrue; executeAtBottomOfEachLoop) {
statementsToExecute
}
|
At the beginning of the loop, the initialization statement is executed (multiple initialization statements can be separated by commas). So long as loopWhileTrue (a Java conditional expression that must evaluate to either true or false) is true, the loop will be executed. At the bottom of the loop, executeAtBottomOfEachLoop is executed.
If you wanted to change a main() method to execute three times, you could use a for loop, as shown in Listing 9:
Listing 9. A
for loop
public static void main(String[] args) {
Logger l = Logger.getLogger(Person.class.getName());
for (int aa = 0; aa < 3; aa++) {
Person p = new Person("Joe Q Author", 42, 173, 82, "Brown", "MALE");
l.info("Loop executing iteration# " + aa);
l.info("Name: " + p.getName());
l.info("Age:" + p.getAge());
l.info("Height (cm):" + p.getHeight());
l.info("Weight (kg):" + p.getWeight());
l.info("Eye Color:" + p.getEyeColor());
l.info("Gender:" + p.getGender());
}
}
|
The local variable aa is initialized to zero at the beginning of the listing. This statement executes only once, when the loop is initialized. The loop then continues three times, and each time aa is incremented by one.
As you will see later, an alternate for loop syntax is available for looping over constructs that implement the Iterable interface (such as arrays and other Java utility classes). For now, just note the use of the for loop syntax in Listing 9.
The syntax for a while loop is:
while (loopWhileTrue) {
statementsToExecute
}
|
As you might suspect, while loopWhileTrue evaluates
to true, so the loop will execute. At the top of each iteration (that is, before any statements execute), the condition is evaluated. If true, the loop executes. So it is possible that a while loop will never execute if its conditional expression is not true at least once.
Look again at the for loop in Listing 9. For comparison, Listing 10 codes it using a while loop:
Listing 10. A
while loop
public static void main(String[] args) {
Logger l = Logger.getLogger(Person.class.getName());
int aa = 0;
while (aa < 3) {
Person p = new Person("Joe Q Author", 42, 173, 82, "Brown", "MALE");
l.info("Loop executing iteration# " + aa);
l.info("Name: " + p.getName());
l.info("Age:" + p.getAge());
l.info("Height (cm):" + p.getHeight());
l.info("Weight (kg):" + p.getWeight());
l.info("Eye Color:" + p.getEyeColor());
l.info("Gender:" + p.getGender());
aa++;
}
|
As you can see, a while loop requires a bit more housekeeping than a for loop. You must initialize the aa variable and also remember to increment it at the bottom of the loop.
If you want a loop that will always execute once and then check its conditional expression, try using a do...while loop, as shown in Listing 11:
Listing 11. A
do...while loop
int aa = 0;
do {
Person p = new Person("Joe Q Author", 42, 173, 82, "Brown", "MALE");
l.info("Loop executing iteration# " + aa);
l.info("Name: " + p.getName());
l.info("Age:" + p.getAge());
l.info("Height (cm):" + p.getHeight());
l.info("Weight (kg):" + p.getWeight());
l.info("Eye Color:" + p.getEyeColor());
l.info("Gender:" + p.getGender());
aa++;
} while (aa < 3);
|
The conditional expression (aa < 3) is not checked until the end of the loop.
There are times when you need to bail out of a loop before the conditional expression evaluates to false. This could happen if you were searching an array of Strings for a particular value, and once you found it, you didn't care about the other elements of the array. For those times when you just want to bail, the Java language provides the break statement, as shown in Listing 12:
Listing 12. A
break statement
public static void main(String[] args) {
Logger l = Logger.getLogger(Person.class.getName());
int aa = 0;
while (aa < 3) {
if (aa == 1)
break;
Person p = new Person("Joe Q Author", 42, 173, 82, "Brown", "MALE");
l.info("Loop executing iteration# " + aa);
l.info("Name: " + p.getName());
l.info("Age:" + p.getAge());
l.info("Height (cm):" + p.getHeight());
l.info("Weight (kg):" + p.getWeight());
l.info("Eye Color:" + p.getEyeColor());
l.info("Gender:" + p.getGender());
aa++;
}
|
The break statement takes you to the very next executable statement outside of the loop in which it's located.
In the (simplistic) example in Listing 12, you only want to execute the loop once and bail. You can also skip a single iteration of a loop but continue executing the loop. For that, you need the continue statement, shown in Listing 13:
Listing 13. A
continue statement
public static void main(String[] args) {
Logger l = Logger.getLogger(Person.class.getName());
int aa = 0;
while (aa < 3) {
if (aa == 1)
continue;
else
aa++;
Person p = new Person("Joe Q Author", 42, 173, 82, "Brown", "MALE");
l.info("Loop executing iteration# " + aa);
l.info("Name: " + p.getName());
l.info("Age:" + p.getAge());
l.info("Height (cm):" + p.getHeight());
l.info("Weight (kg):" + p.getWeight());
l.info("Eye Color:" + p.getEyeColor());
l.info("Gender:" + p.getGender());
}
|
In Listing 13, you skip the second iteration of a loop but continued to the third. continue comes in handy when you are, say, processing records and come across a record you definitely don't want to process. Just skip that record and move on to the next one.


