Java: Repetition and the For Loop - dummies

Java: Repetition and the For Loop

By John Paul Mueller

In Java, like in the real world, there are many times when you repeat something. Likewise, applications have a need to repeat tasks. Doing them once isn’t enough, in some cases. This chapter helps you understand how to perform the same task multiple times.

A repetitive loop consists of a special structure that tracks when to begin and end a series of repetitive tasks, and the tasks within that structure.

The for loop repeats a series of tasks a specific number of times and a while loop continues to repeat a series of tasks until a specific condition is met. The for-next loop is special in that it works with each element in an enumeration, array, or collection.

A structure starts with a statement that specifies the purpose of the structure, such as a repetitive loop. The structure body starts with an opening curly brace ({) and ends with a closing curly brace (}). One or more lines of code that describe one or more tasks to perform appear between the two braces, in the body of the structure. Structures are used for a number of purposes throughout the book.

It’s possible to perform every sort of repetitive loop using a for loop, but doing so would mean writing your code in odd ways. Even so, the for loop is the workhorse of the repetitive loop structures because it’s easy to create, easy to debug, and easy to understand. The essence of a for loop is that the application performs a series of tasks a specific number of times.

It’s important to understand how a for loop is put together before you create your first one. The for loop begins with the word “for” followed by parentheses containing the following three items, separated by semicolons (;):

  • A counter variable and the code used to initialize it, such as int Current = 1.

  • A condition that will end the loop after a specific count, such as Current <= 5.

  • A method for updating the counter variable so that the for loop can keep track of the current count, such as Current++.

A counter variable is a variable whose whole purpose is to track the current count of something. The variable doesn’t actually add or subtract anything from the application data; rather, the purpose of the counter variable is to help the application perform the tasks you assign to it.

The set of curly braces used to define the beginning and end of the for loop appears next. You place your code within the curly braces.