Certification Objective Loops and Iterators (Exam Objective 2.2)


Certification Objective —Loops and Iterators (Exam Objective 2.2)

2.2 Develop code that implements all forms of loops and iterators, including the use of for, the enhanced for loop (for-each), do, while, labels, break, and continue; and explain the values taken by loop counter variables during and after loop execution.

Java loops come in three flavors: while, do, and for (and as of Java 5, the for loop has two variations). 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.

Using while Loops

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 } 

or

 int x = 2; while(x == 2) {   System.out.println(x);   ++x; } 

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. In the previous example, program control will enter the loop body because x is equal to 2. However, x is incremented in the loop, so when the condition is checked again it will evaluate to false and exit the loop.

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) { }   // not legal 

Then again, why would you? Instead of testing the variable, you'd be declaring and initializing it, so it would always have the exact same value. Not much of a test condition!

The key point to remember about a while loop is that it might not ever run. 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.

Using do 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 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.

image from book
Exam Watch

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 

image from book

Using for Loops

As of Java 5, the for loop took on 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" (even though the Sun objective 2.2 refers to it as the for-each). Depending on what documentation you use (Sun's included), you'll see both terms, along with for-in. The terms for-in, for-each, and "enhanced for" all refer to the same Java construct.

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                          // and can't be accessed. 

If you try to compile this, you'll get something like this:

 Test.java:19: cannot resolve symbol symbol  :  variable x location:  class Test   System.out.println(x);                      ^ 

Basic for Loop: Conditional (Boolean) 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:

 TestLong.java:20: ';' 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 doStuff() {   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. Table 5-1 lists the causes and results of abrupt loop termination.

Table 5-1: Causes of Early Loop Termination

Code in Loop

What Happens

break

Execution jumps immediately to the 1st statement after the for loop.

return

Execution jumps immediately back to the calling method.

System.exit()

All program execution stops; the VM shuts down.

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;)   i++;   //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); } 

image from book
Exam Watch

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

image from book

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("iterate")) {   b = b - a; } 

The preceding code prints

 iterate iterate 

image from book
Exam Watch

Many questions in the new (Java 5) exam list "Compilation fails" and "An exception occurs at runtime" as possible answers. This makes it more difficult because you can't simply work through the behavior of the code. You must first make sure the code isn't violating any fundamental rules that will lead to compiler error, and then look for possible exceptions. Only after you've satisfied those two, should you dig into the logic and flow of the code in the question.

image from book

The Enhanced for Loop (for Arrays)

The enhanced for loop, new to Java 5, 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. In Chapter 7 we'll revisit the enhanced for as we discuss collections—where the enhanced for really comes into its own.

Instead of having three components, the enhanced for has two. Let's loop through an array the basic (old) way, and then using the enhanced for:

 int [] a = {1,2,3,4}; for(int x = 0; x < a.length; x++)   // basic for loop   System.out.print(a[x]); for(int n : a)                      // enhanced for loop   System.out.print(n); 

Which produces this output:

 12341234 

More formally, let's describe the enhanced for as follows:

 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:

 int x; long x2; Long [] La = {4L, 5L, 6L}; long [] la = {7L, 8L, 9L}; int [][] twoDee = {{1,2,3}, {4,5,6}, {7,8,9}}; String [] sNums = {"one", "two", "three"}; Animal [] animals = {new Dog(), new Cat()}; // legal 'for' declarations for(long y : la ) ;        // loop thru an array of longs for(long lp : La);         // autoboxing the Long objects                            // into longs for(int[] n : twoDee);     // loop thru the array of arrays for(int n2 : twoDee[2]);   // loop thru the 3rd sub-array for(String s : sNums);     // loop thru the array of Strings for(Object o : sNums);     // set an Object reference to                            // each String for(Animal a : animals);   // set an Animal reference to each                            // element // ILLEGAL 'for' declarations for(x2 : la);              // x2 is already declared for(int x2 : twoDee);      // can't stuff an array into an int for(int x3 : la);          // can't stuff a long into an int for(Dog d : animals);      // you might get a Cat! 

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.

image from book
Exam Watch

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

image from book

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");   continue; } 

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. doStuff() == 5) {     continue;   }   // more loop code, that won't be reached when the above if   // test is true } 

Unlabeled Statements

Both the break statement and the continue statement can be unlabeled or labeled. Although it's far more common to use break and continue unlabeled, the exam expects you to know how labeled break and continue statements work. As stated before, a break statement (unlabeled) will exit out of the innermost looping construct and proceed with the next line of code beyond the loop block. The following example demonstrates a break statement:

 boolean problem = true; while (true) {   if (problem) {     System.out.println("There was a problem");     break;   } } // next line of code 

In the previous example, the break statement is unlabeled. The following is an example of an unlabeled continue statement:

 while (!EOF) {   //read a field from a file   if (wrongField) {     continue;    // move to the next field in the file   }   // otherwise do other stuff with the field } 

In this example, a file is being read one field at a time. When an error is encountered, the program moves to the next field in the file and uses the continue statement to go back into the loop (if it is not at the end of the file) and keeps reading the various fields. If the break command were used instead, the code would stop reading the file once the error occurred and move on to the next line of code after the loop. The continue statement gives you a way to say, "This particular iteration of the loop needs to stop, but not the whole loop itself. I just don't want the rest of the code in this iteration to finish, so do the iteration expression and then start over with the test, and don't worry about what was below the continue statement."

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. An example of what a label looks like is in the following code:

 foo:   for (int x = 3; x < 20; x++) {     while(y > 7)    {       y--;     }   } 

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 is True = true; outer:   for(int i=0; i<5; i++) {     while (isTrue) {       System.out.println("Hello");       break outer;     } // end of inner while loop     System.out.println("Outer loop."); // Won't print   } // end of outer for loop System.out.println("Good-Bye"); 

Running this code produces

 Hello Good-Bye 

In this example the word Hello 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 Good-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:

 outer:   for (int i=0; i<5; 1++) {     for (int j=0; j<5; j++) {       System.out.println("Hello");       continue outer;     } // end of inner loop     System.out.println("outer"); // Never prints   } System.out.println("Good-Bye"); 

Running this code produces

 Hello Hello Hello Hello Hello Good-Bye 

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.

Exercise 5-2: Creating a Labeled while Loop

image from book

Try creating a labeled while loop. Make the label outer and provide a condition to check whether a variable age is less than or equal to 21. Within the loop, increment age by one. Every time the program goes through the loop, check whether age is 16. If it is, print the message "get your driver's license" and continue to the outer loop. If not, print "Another year."

  • The outer label should appear just before the while loop begins.

  • Make sure age is declared outside of the while loop.

image from book

image from book
Exam Watch

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

image from book




SCJP Sun Certified Programmer for Java 5 Study Guide Exam 310-055
SCJP Sun Certified Programmer for Java 5 Study Guide (Exam 310-055) (Certification Press)
ISBN: 0072253606
EAN: 2147483647
Year: 2006
Pages: 131

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net