Home arrow Java arrow Page 9 - Making Decisions, Decisions

Making Decisions, Decisions

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).

Author Info:
By: Apress Publishing
Rating: 4 stars4 stars4 stars4 stars4 stars / 11
May 05, 2005
  1. · Making Decisions, Decisions
  2. · Creating Multidimensional Arrays
  3. · Comparing Data Values
  4. · Making Decisions
  5. · Understanding Variable Scope in Statement Blocks
  6. · How It Works
  7. · Understanding the Conditional Operator
  8. · Trying It Out: Working with the choose...when...when Construct
  9. · Understanding Loops and Iteration
  10. · Introducing Branching Statements
  11. · Trying It Out: Using Arrays

print this article

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()) {

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:

  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)
  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;
  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.

Using the for Statement

The for statement syntax is as follows:

for(initialization; termination; increment)
  Statement Block

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++)

The output of this would be as follows:


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:

<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core_rt" %>
<c:forEach begin="3" end="15" step="3" var="index" varStatus="num">
  <c:out value="${index}" />:<c:out value="${num.count}" /> </c:forEach>

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)

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:


This process is often called iterating through the array.

blog comments powered by Disqus

- Java Too Insecure, Says Microsoft Researcher
- Google Beats Oracle in Java Ruling
- Deploying Multiple Java Applets as One
- Deploying Java Applets
- Understanding Deployment Frameworks
- Database Programming in Java Using JDBC
- Extension Interfaces and SAX
- Entities, Handlers and SAX
- Advanced SAX
- Conversions and Java Print Streams
- Formatters and Java Print Streams
- Java Print Streams
- Wildcards, Arrays, and Generics in Java
- Wildcards and Generic Methods in Java
- Finishing the Project: Java Web Development ...

Watch our Tech Videos 
Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Weekly Newsletter
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 

Developer Shed Affiliates


© 2003-2017 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials