Most JavaServer Pages will need to perform one of several actions according to some condition. This is managed in the code through control statements, which come in three flavors: conditional, iterative, and branching. This article will explain the syntax Java provides for these statements, how and when to use arrays, and more. It is taken from chapter five of Beginning JSP 2 From Novice to Professional, written by Peter den Haan et. al. (Apress, 2004; ISBN: 1590593391).
Making Decisions, Decisions - Understanding Loops and Iteration (Page 9 of 11 )
There are many programming situations where you need to execute the same logic repeatedly. Although you could simply write the code several times in sequence, this is clearly not a great idea. First, there’s a much greater chance that you’ll make an error in one of the duplicated blocks, and that error would consequently be harder to track down because there’d be no clear indication of which duplicated block contained the error. Second, in many cases, you rarely know in advance how many times you need to repeat the same steps. Consequently, just about every programming language has constructs that allow a single block of code to be repeated a given number of times.
Executing the same block of code over and over is known as iteration, or looping. Java has three types of iterative logic, each represented by one of the following statements:
while statements
do...while statements
for statements
You’ll look at each of these in the following sections.
Using the while Loop
In many situations, you want to repeat a block of code for as long as a given expression remains true, and in such cases, you can use the while loop. Its syntax is pretty simple:
while (expression) { Statement Block }
For example, the following while loop will print the authors of each book returned from the database (rs.next() moves on to the next record returned from the database):
// Now we get the data ResultSet rs = stmt.executeQuery("SELECT * FROM books"); // We need to iterate over the ResultSet while (rs.next()) { rs.getString("author") }
You have an integer variable, count, which you initialize to 1. The while statement itself says that the statement block should be executed over and over until the value of count reaches 6. Each time you loop through the statement block, the value of count is displayed and 1 is added to count, so count will be displayed five times before the while expression returns false.
You’ll now move on and look at a variation of the while statement: the do...while statement.
Using the do...while Loop
Using do...while loops are similar to using while loops, and they repeat a block of code for as long as an expression remains true. The difference is that do...while loops check the value of the expression after the code block, not before as in the plain while loop. This really just means that the code block will always execute at least once (even if the condition isn’t true when the loop is first encountered).
A pitfall of do...while loops in Java is that a semicolon is required at the end of the while statement, which is something that’s frequently forgotten:
do { Statement Block } while (expression);
You’ll now return to the simplistic while loop that counts up to five. Consider what would happen if you initialize the count variable to 6 instead of 1:
int count = 6; while (count < 6) { System.out.println(count); count = count + 1; }
Because the while loop will iterate only while the value of count is less than six, setting the initial value to 6 means that the loop never gets executed.
Now consider what happens if you set up the same counting example using a do...while loop:
int count = 6; do { System.out.println(count); count = count + 1; } while (count < 6);
In this case, because the expression isn’t checked until the end of the loop, one iteration is allowed to occur, and you can see the value of count displayed, 6.
NOTE Use the while loop when you need the condition to be checked before executing the code block, and use do...while when the code block should execute at least once.
The while and do...while constructs let you create general-purpose loops that can be applied to a range of situations. However, in many cases, you want to repeat a block of code a certain number of times and, on each pass through the loop, use the current loop count in some code. Such situations are ideally suited to the for loop.
Key to how for loops work is a counter variable. You can set this variable to a value on entering the loop, and it’ll be increased or decreased by a certain amount at the end of each execution of the code block forming the body of the loop. There’s also a test that determines when enough loops have been performed.
This is a simple example of a for loop:
for (int num = 1; num <= 5; num++) { System.out.println(num); }
The output of this would be as follows:
1 2 3 4 5
In this case, the loop uses a counter variable called num, which is declared and initialized to 1 in the first expression in the brackets following the for statement. This expression is the initialization expression, and it’s followed by what’s called the termination expression. The termination expression gives a condition that must evaluate to true for the code in the loop body to be executed (in this case, the loop will continue for as long as num is less than or equal to five). The last expression of the for syntax is the increment expression, which is executed every time the end of the loop body is reached (and here, increments num by one).
The for statement is very flexible. The increment expression can be any expression that should be executed at the end of each iteration and need not involve the loop counter at all. The initialization expression can set the counter to any value you choose, and you can use any numerical type as well as integers. You can, of course, use other variables in any of the three for expressions.
As you can see, the for loop’s initialization expression declares and initializes num, but this isn’t a requirement; you can just as well use an already existing variable as the counter, and you can even use its existing value by using a “blank” initialization expression:
int num = 1; for (; num <= 5; num++)
The JSTL implements for loops using the <forEach> tag. Given the concepts of for statements just discussed, you should be able to deduce the purpose of most of the attributes shown in the following tag:
If you type the previous code into a text file and save it as forexample.jsp in your Decisions directory, it’ll produce the output shown in Figure 5-8 when opened in a browser.
Figure 5-8.The JSTL’s <forEach> tag in action
As you can see, this tag in fact requires two variables to function correctly, and you specify which names to give these using the var and varStatus attributes. varStatus specifies the name to use for the loop counter, and var is used internally by the JSTL.
This <forEach> loop mirrors the following Java for loop:
for (num = 3; num <= 15; num += 3) System.out.println(num);
We’ll cover other uses of the <forEach> tag later in the “Trying It Out: Using Arrays” section.
Iterating Through Arrays
The for loop is useful when you need to process each element in an array and is often used in conjunction with the length property. This property tells you how many elements the array contains, and therefore you can use it in the termination expression:
for(int index = 0; index < thisIsAnArray.length; index++)
Note that length will return the declared size of the array, regardless of how many array elements have been initialized. The for loop is particularly suited to arrays because in the loop body, you can use the counter variable to process each element in turn, like so:
System.out.println(moreNumbers[index]);
This process is often called iterating through the array.