FOR Loop
The first loop we’re going to look at is the for loop. Both Pascal and Basic have for loops, as do C and C++. Like those languages, the for loop in Java is designed for writing counted loops–loops that repeat a specified number of times.
Unlike the Pascal or Basic for loop, however, the for loop in Java can do much more than simple counted loops. The for loop in Java works almost exactly like the for loop in C++; it is a general purpose, “test at the top” loop, that makes writing counted loops very straightforward, but can be used for other purposes.
Syntax
As mentioned previously, the body of the for loop follows the loop’s test condition; you test first, then, if the test evaluates to true, you enter the loop body, as you can see in the illustration. [click image to enlarge]
The for loop’s condition involves more than a simple boolean test, however. In fact, it involves three different expressions:
- The initialization expression
- The test expression
- The update expression
Each of these three expressions is separated from the others by a semicolon. You can omit any–or all–of the expressions, but the semicolons are required. [Make sure that you don’t accidentally use commas instead of semicolons. When you do so, the javac compiler is not particularly helpful with its error messages]
The loop body following the loop condition is usually enclosed in braces, although, technically, braces are not required if the loop body consists of a single statement. As a practical matter, though, you’ll almost always use braces, and, since they don’t hurt–even when not strictly required–you should always put them in as a matter of course.
Let’s return to the for loop condition, and take a closer look at each of its three expressions.
The Initialization Expression
When a for loop is encountered, the first part of the loop condition, the initialization expression, is executed. It is always executed, regardless of the other parts of the for statement, almost as if it occurred on the previous line.
The initialization expression is evaluated only once, and is usually used to define the counter variable that will control your loop, like this:
The for Loop Initialization Expression |
for (int counter = 0; ... ; ...)
{
// Can use counter here
}
// Cannot use counter here |
Variables declared inside the for loop initialization section, like counter, shown here, are local to the body of the for loop. Once the loop is finished, the variable goes out of scope and can no longer be used.
The boolean Test
The second section of the for loop is called the test condition. The test condition is a boolean expression which is evaluated immediately after the initialization expression.
If the test condition is true, [when it is evaluated], then execution begins with the first statement in the loop. If it is false, then the entire loop body is skipped, and execution continues at the first statement following the loop body.
To continue our example, we can test the value of counter, checking to make sure it is less than ten:
The for Loop Test Expression |
for (int counter = 0;
counter < 10 ; ...)
{
// Can use counter here
}
// Cannot use counter here |
Using counter like this insures that the loop will execute ten times. This is a common idiom in Java programming:
- start counter at 0
- test that counter is less than the upper bounds
An idiom is just a common and widely accepted way of “phrasing” a particular operation. This particular idiom works well, because you can immediately tell how many times the loop will execute just by glancing at the test condition.
The Update Expression
In Lesson 6.1, “Introduction to Loops”, you learned to make sure that every repetition of a loop moves closer to the loop bounds. But, in the for loop shown here, there are nostatements that move toward the bounds; in fact, as written, this example is an endless loop! Since counter is never updated, it always remains at zero.
Updating the counter is the responsibility of the third part of the for loop condition–the update expression. The update expression is evaluated after the body of the loop is finished, but before the test expression is evaluated for the next repetition.
For a counted loop, you’ll use the test expression to update your counter like this:
The for Loop Update Expression |
for (int counter = 0;
counter < 10 ;
++counter)
{
// Can use counter here
}
// Cannot use counter here |
Counting Variations
You’ve probably noticed that this loop doesn’t really do anything; the portion that we’ve written simply repeats ten times. However, you can use this basic skeleton for any loop that needs to repeat a fixed number of times. Simply replace 10 with the number of times you want to repeat, and you’re all set.
In addition to acting as a loop control, you can also use your counter variable to process different pieces of information during each repetition of the loop. Here, for instance, is a loop that sums the Unicode values for all the characters in a String:
Using the for Loop |
String s = myTF.getText();
int nChars = s.length();
int sumOfCodes = 0;for (int counter= 0; counter < nChars ; ++counter)
{
sumOfCodes += s.charAt(counter);
}myTF.setText("Sum of codes = " + sumOfCodes);How much is your name worth? Type your name into the text area shown below, and press ENTER. The applet shown here [SumOfCodes.java] will total up the Unicode values for each of the characters in your name, and display your “weight” in Unicode.
|
Counting Down
When you create a counted loop using for, you are responsible for initializing the counter in the intitialization expression, and for updating it in the update expression. There’s no law that says you have to start at zero, and there’s nothing to stop you from counting down rather than up.
Here’s a fragment that displays the characters in a String in reverse order. It works by walking through the characters of the String from the end to the beginning, using a for loop to count down, instead of counting up.
Counting Down With the for Loop |
String s = myTF.getText();
int nChars = s.length();
String output = "";for (int counter = nChars - 1;
counter >= 0 ;
--counter)
{
output += s.charAt(counter);
}outputLbl.setText(output);Type in a phrase, press ENTER, and the applet shown here [ReverseString.java] will reverse it, thanks to the magic of the for loop. |
What’s with the -1? |
You might wonder why the code shown here subtracts one from the length of the String in the initialization expression. In a String, the characters are numbered starting with zero. Thus, if there are 10 characters in a particular String, then the last character is in position 9. |
|
Counting by Steps
Not only can you count up and count down, you can also count by values other than 1 simply by changing the value in the update expression. The Basic language allows you do do this via its STEP clause, but the Java for loop allows you to use any expression you like, not just different constant values.
Here, for instance, is how you could calculate the sum of all the even numbers less than 100:
Sum = 0;
for (int i = 0; i < 100; i += 2)
{
Sum += i;
} |
And, here’s a loop that displays exponential growth. How many numbers do you think that this will print?
for (int i = 2; i < 10000; i *= i)
{
System.out.println(i);
} |