HomeJava & J2EE Page 4 - The JSP Files (part 3): Black Light And White Rabbits
The Sound Of Breaking Loops - Java
This week, learn all about the different types of loops supportedby JSP, and also expand your knowledge of the various String objectmethods. Finally, take a quick tour of the JSP Response object inpreparation for learning how JSP handles form data.
When dealing with loops, there are two important keywords you should be aware of: "break" and "continue".
The "break" keyword is used to exit a loop when it encounters an unexpected situation. A good example of this is the dreaded "division by zero" error - when dividing one number by another one (which keeps decreasing), it is advisable to check the divisor and use the "break" statement to exit the loop as soon as it becomes equal to zero.
As you've already seen, the "continue" keyword is used to skip a particular iteration of the loop and move to the next iteration immediately - it's demonstrated in the following example:
<%
int x;
for (x=1; x<=10; x++)
{
if (x == 7)
{
continue;
}
else
{
out.println(x + "");
}
}
%>
In this case, JSP will print a string of numbers from
1 to 10 - however, when it hits 7, the "continue" statement will cause it to skip that particular iteration and go back to the top of the loop. So your string of numbers will not include 7 - try it and see for yourself.