Saturday, February 5, 2011

Chapter 28: Loops and Iterators

Java loops come in three flavors: while, do, and for. All three let you repeat a block of code as long as some condition is true, or for a specific number of iterations. You’re probably familiar with loops from other languages, so even if you’re somewhat new to Java, these won’t be a problem to learn this topic. Let us get started with the loops.

while Loop

The while loop is good for scenarios where you don’t know how many times a block or statement should repeat, but you want to continue looping as long as some condition is true. A while statement looks like this:
while (expression) {
// do stuff

In this case, as in all loops, the expression (test) must evaluate to a boolean result. The body of the while loop will only execute if the expression (sometimes called the “condition”) results in a value of true. Once inside the loop, the loop body will repeat until the condition is no longer met because it evaluates to false.

Any variables used in the expression of a while loop must be declared before the expression is evaluated. In other words, you can’t say

while (int x = 2) { } // This is not legal

The key point to remember about a while loop is that it might not run at all. If the test expression is false the first time the while expression is checked, the loop body will be skipped and the program will begin executing at the first statement after the while loop. Look at the following example:

int x = 8;
while (x > 8) {
System.out.println("in the loop");
x = 10;
System.out.println("past the loop");

Running this code produces
past the loop

Because the expression (x > 8) evaluates to false, none of the code within the while loop ever executes.

Do-while Loops

The do loop is similar to the while loop, except that the expression is not evaluated until after the do loop’s code is executed. Therefore the code in a do loop is guaranteed to execute at least once. The following shows a do loop in action:

do {
System.out.println("Inside do while loop");
} while(false);

The System.out.println() statement will print once, even though the expression evaluates to false. Remember, the do loop will always run the code in the loop body at least once. Be sure to note the use of the semicolon at the end of the while expression.

Exam Tip:
As with if tests, look for while loops (and the while test in a do loop) with an expression that does not resolve to a boolean. Take a look at the following examples of legal and illegal while expressions:
int x = 1;
while (x) { } // Won't compile; x is not a boolean
while (x = 5) { } // Won't compile; resolves to 5
//(as the result of assignment)
while (x == 5) { } // Legal, equality test
while (true) { } // Legal

for Loops

As of Java 6, the for loop has a second structure. We’ll call the old style of for loop the “basic for loop”, and we’ll call the new style of for loop the “enhanced for loop”. It is also called the for-each loop.

The basic for loop is more flexible than the enhanced for loop, but the enhanced for loop was designed to make iterating through arrays and collections easier to code.

The Basic for Loop

The for loop is especially useful for flow control when you already know how many times you need to execute the statements in the loop’s block. The for loop declaration has three main parts, besides the body of the loop:
• Declaration and initialization of variables
• The boolean expression (conditional test)
• The iteration expression

The three for declaration parts are separated by semicolons. The following two examples demonstrate the for loop. The first example shows the parts of a for loop in a pseudocode form, and the second shows a typical example of a for loop.
for (/*Initialization*/ ; /*Condition*/ ; /* Iteration */) {
/* loop body */


for (int i = 0; i<10; i++) {

System.out.println("i is " + i);


The Basic for Loop: Declaration and Initialization

The first part of the for statement lets you declare and initialize zero, one, or multiple variables of the same type inside the parentheses after the for keyword. If you declare more than one variable of the same type, then you’ll need to separate them with commas as follows:

for (int x = 10, y = 3; y > 3; y++) { }

The declaration and initialization happens before anything else in a for loop. And whereas the other two parts—the boolean test and the iteration expression—will run with each iteration of the loop, the declaration and initialization happens just once, at the very beginning. You also must know that the scope of variables declared in the for loop ends with the for loop! The following demonstrates this:

for (int x = 1; x < 2; x++) {

System.out.println(x); // Legal


System.out.println(x); // Not Legal! x is now out of scope

If you try to compile this, you’ll get something like this: cannot resolve symbol

symbol : variable x

location: class Test


Basic for Loop: Conditional Expression

The next section that executes is the conditional expression, which (like all other conditional tests) must evaluate to a boolean value. You can have only one logical expression, but it can be very complex. Look out for code that uses logical expressions like this:

for (int x = 0; ((((x < 10) && (y-- > 2)) | x == 3)); x++) { }

The preceding code is legal, but the following is not:
for (int x = 0; (x > 5), (y < 2); x++) { } // too many //expressions

The compiler will let you know the problem: ';' expected

for (int x = 0; (x > 5), (y < 2); x++) { }

The rule to remember is this: You can have only one test expression.

In other words, you can’t use multiple tests separated by commas, even though the other two parts of a for statement can have multiple parts.

Basic for Loop: Iteration Expression

After each execution of the body of the for loop, the iteration expression is executed. This is where you get to say what you want to happen with each iteration of the loop. Remember that it always happens after the loop body runs! Look at the following:
for (int x = 0; x < 1; x++) {

// body code that doesn't change the value of x


The preceding loop executes just once. The first time into the loop x is set to 0, then x is tested to see if it’s less than 1 (which it is), and then the body of the loop executes. After the body of the loop runs, the iteration expression runs, incrementing x by 1. Next, the conditional test is checked, and since the result is now false, execution jumps to below the for loop and continues on.

Keep in mind that barring a forced exit, evaluating the iteration expression and then evaluating the conditional expression are always the last two things that happen in a for loop!

Examples of forced exits include a break, a return, a System.exit(), or an exception, which will all cause a loop to terminate abruptly, without running the iteration expression. Look at the following code:

static boolean doSomething() {

for (int x = 0; x < 3; x++) {

System.out.println("in for loop");

return true;


return true;


Running this code produces

in for loop

The statement only prints once, because a return causes execution to leave not just the current iteration of a loop, but the entire method. So the iteration expression never runs in that case.

Basic for Loop: for Loop Issues

None of the three sections of the for declaration are required! The following example is perfectly legal (although not necessarily good practice):

for( ; ; ) {

System.out.println("Inside an endless loop");


In the preceding example, all the declaration parts are left out so the for loop will act like an endless loop. For the exam, it’s important to know that with the absence of the initialization and increment sections, the loop will act like a while loop. The following example demonstrates how this is accomplished:

int i = 0;

for (;i<10;) {


//do some other work


The next example demonstrates a for loop with multiple variables in play. A comma separates the variables, and they must be of the same type. Remember that the variables declared in the for statement are all local to the for loop, and can’t be used outside the scope of the loop.

for (int i = 0,j = 0; (i<10) && (j<10); i++, j++) {

System.out.println("i is " + i + " j is " +j);


The last thing to note is that all three sections of the for loop are independent of each other. The three expressions in the for statement don’t need to operate on the same variables, although they typically do. But even the iterator expression, which many mistakenly call the “increment expression,” doesn’t need to increment or set anything; you can put in virtually any arbitrary code statements that you want to happen with each iteration of the loop. Look at the following:

int b = 3;

for (int a = 1; b != 1; System.out.println("hii")) {

b = b - a;


The preceding code prints


Exam Tip:
Variable scope plays a large role in the exam. You need to know that a variable declared in the for loop can’t be used beyond the for loop. But a variable only initialized in the for statement (but declared earlier) can be used beyond the loop. For example, the following is legal,
int x = 3;
for (x = 12; x < 20; x++) { } System.out.println(x); while this is not for (int x = 3; x < 20; x++) { } System.out.println(x);

The Enhanced for Loop – For Arrays

The enhanced for loop, new to Java 6, is a specialized for loop that simplifies looping through an array or a collection. In this chapter we’re going to focus on using the enhanced for to loop through arrays. We’ll revisit the enhanced for as we discuss collections in the future chapter.
Instead of having three components, the enhanced for has two.
for(declaration : expression)

The two pieces of the for statement are

• declaration The newly declared block variable, of a type compatible with the elements of the array you are accessing. This variable will be available within the for block, and its value will be the same as the current array element.
• expression This must evaluate to the array you want to loop through. This could be an array variable or a method call that returns an array. The array can be any type: primitives, objects, even arrays of arrays.
Using the above definitions, let’s look at some legal and illegal enhanced for declarations:
String [] sNums = {"one", "two", "three"};

// legal 'for' declarations
for(String s : sNums) ; // loop thru the array of Strings

The enhanced for loop assumes that, barring an early exit from the loop, you’ll always loop through every element of the array. The following discussions of break and continue apply to both the basic and enhanced for loops.

Using break and continue

The break and continue keywords are used to stop either the entire loop (break) or just the current iteration (continue). Typically if you’re using break or continue, you’ll do an if test within the loop, and if some condition becomes true (or false depending on the program), you want to get out immediately. The difference between them is whether or not you continue with a new iteration or jump to the first statement below the loop and continue from there.

Exam Tip:
Remember, continue statements must be inside a loop; otherwise, you’ll get a compiler error. break statements must be used inside either a loop or switch statement. (Note: this does not apply to labeled break statements.).

The break statement causes the program to stop execution of the innermost loop and start processing the next line of code after the block.

The continue statement causes only the current iteration of the innermost loop to cease and the next iteration of the same loop to start if the condition of the loop is met. When using a continue statement with a for loop, you need to consider the effects that continue has on the loop iteration. Examine the following code:

for (int i = 0; i < 10; i++) {

System.out.println("Inside loop");



The question is, is this an endless loop? The answer is no. When the continue statement is hit, the iteration expression still runs! It runs just as though the current iteration ended “in the natural way.” So in the preceding example, i will still increment before the condition (i < 10) is checked again. Most of the time, a continue is used within an if test as follows:

for (int i = 0; i < 10; i++) {

System.out.println("Inside loop");

if (foo.doSomething() == 5) {



// more loop code, that won't be reached when the above if

// test is true


Labeled Statements

Although many statements in a Java program can be labeled, it’s most common to use labels with loop statements like for or while, in conjunction with break and continue statements. A label statement must be placed just before the statement being labeled, and it consists of a valid identifier that ends with a colon (:).

You need to understand the difference between labeled and unlabeled break and continue. The labeled varieties are needed only in situations where you have a nested loop, and need to indicate which of the nested loops you want to break from, or from which of the nested loops you want to continue with the next iteration. A break statement will exit out of the labeled loop, as opposed to the innermost loop, if the break keyword is combined with a label.

The label must adhere to the rules for a valid variable name and should adhere to the Java naming convention. The syntax for the use of a label name in conjunction with a break statement is the break keyword, then the label name, followed by a semicolon. A more complete example of the use of a labeled break statement is as follows:

boolean isTrue = true;


for(int i=0; i<5; i++) {

while (isTrue) {


break outer;

} // end of inner while loop

System.out.println("Outer loop.");

} // end of outer for loop


Running this code produces



In this example the word Hi will be printed one time. Then, the labeled break statement will be executed, and the flow will exit out of the loop labeled outer. The next line of code will then print out Bye. Let’s see what will happen if the continue statement is used instead of the break statement. The following code example is similar to the preceding one, with the exception of substituting continue for break:


for (int i=0; i<5; i++) {

for (int j=0; j<5; j++) {


continue outer;

} // end of inner loop

System.out.println("outer"); // Never prints



Running this code produces







In this example, Hello will be printed five times. After the continue statement is executed, the flow continues with the next iteration of the loop identified with the label. Finally, when the condition in the outer loop evaluates to false, this loop will finish and Good-Bye will be printed.

Exam Tip:
Labeled continue and break statements must be inside the loop that has the same label name; otherwise, the code will not compile.

Previous Chapter: Chapter 27 - If and Switch Statements

Next Chapter: Chapter 29 - Exception Handling

No comments:

Post a Comment

© 2013 by All rights reserved. No part of this blog or its contents may be reproduced or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, or otherwise, without prior written permission of the Author.


Google+ Followers