Chapter 5

Réussis tes devoirs et examens dès maintenant avec Quizwiz!

The if else ladder

A common programming construct that is based upon a sequence of nested ifs is the if-else- if ladder. It looks like this: if(condition) statement; else if(condition) statement; else if(condition) statement; . . . else statement; The if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the ladder is bypassed. If none of the conditions is true, then the final else statement will be executed. The final else acts as a default condition; that is, if all other conditional tests fail, then the last else statement is performed. If there is no final else and all other conditions are false, then no action will take place.

Nested ifs

A nested if is an if statement that is the target of another if or else. Nested ifs are very common in programming. When you nest ifs, the main thing to remember is that an else statement always refers to the nearest if statement that is within the same block as the else and that is not already associated with an else. Here is an example: if(i == 10) { if(j < 20) a = b; if(k > 100) c = d; // this if is else a = c; // associated with this else } else a = d; // this else refers to if(i == 10) As the comments indicate, the final else is not associated with if(j<20) because it is not in the same block (even though it is the nearest if without an else). Rather, the final else is associated with if(i==10). The inner else refers to if(k>100) because it is the closest if within the same block.

Using breaks as a form of goto

In addition to its uses with the switch statement and loops, the break statement can also be employed by itself to provide a "civilised" form of the goto statement. Java does not have a goto statement because it provides a way to branch in an arbitrary and unstructured manner. This usually makes goto-ridden code hard to understand and hard to maintain. It also prohibits certain compiler optimisations. There are, however, a few places where the goto is a valuable and legitimate construct for flow control. For example, the goto can be useful when you are exiting from a deeply nested set of loops. To handle such situations, Java defines an expanded form of the break statement. By using this form of break, you can, for example, break out of one or more blocks of code. These blocks need not be part of a loop or a switch. They can be any block. Further, you can specify precisely where execution will resume, because this form of break works with a label. As you will see, break gives you the benefits of a goto without its problems. The general form of the labeled break statement is shown here: break label; Most often, label is the name of a label that identifies a block of code. This can be a stand- alone block of code but it can also be a block that is the target of another statement. When this form of break executes, control is transferred out of the named block. The labeled block must enclose the break statement, but it does not need to be the immediately enclosing block. This means, for example, that you can use a labeled break statement to exit from a set of nested blocks. But you cannot use break to transfer control out of a block that does not enclose the break statement. To name a block, put a label at the start of it. A label is any valid Java identifier followed by a colon. Once you have labeled a block, you can then use this label as the target of a break statement. Doing so causes execution to resume at the end of the labeled block. For example, the following program shows three nested blocks, each with its own label. The break statement causes execution to jump forward, past the end of the block labeled second, skipping the two println( ) statements. // Using break as a civilized form of goto. class Break { public static void main(String args[]) { boolean t = true; first: { second: { third: { System.out.println("Before the break."); if(t) break second; // break out of second block System.out.println("This won't execute"); } System.out.println("This won't execute"); } System.out.println("This is after second block."); } } } Running this program generates the following output: Before the break. This is after second block. One of the most common uses for a labeled break statement is to exit from nested loops. For example, in the following program, the outer loop executes only once: // Using break to exit from nested loops class BreakLoop4 { public static void main(String args[]) { outer: for(int i=0; i<3; i++) { System.out.print("Pass " + i + ": "); for(int j=0; j<100; j++) { if(j == 10) break outer; // exit both loops System.out.print(j + " "); } System.out.println("This will not print"); } System.out.println("Loops complete."); } } This program generates the following output: Pass 0: 0 1 2 3 4 5 6 7 8 9 Loops complete. As you can see, when the inner loop breaks to the outer loop, both loops have been terminated. Notice that this example labels the for statement, which has a block of code as its target. Keep in mind that you cannot break to any label which is not defined for an enclosing block. For example, the following program is invalid and will not compile: // This program contains an error. class BreakErr { public static void main(String args[]) { one: for(int i=0; i<3; i++) { System.out.print("Pass " + i + ": "); } for(int j=0; j<100; j++) { if(j == 10) break one; // WRONG System.out.print(j + " "); } } } Since the loop labeled one does not enclose the break statement, it is not possible to transfer control out of that block.

Using break

In Java, the break statement has three uses. First, as you have seen, it terminates a statement sequence in a switch statement. Second, it can be used to exit a loop. Third, it can be used as a "civilised" form of goto.

Jump statements

Java supports three jump statements: break, continue and return. These statements transfer control to another part of your program

Iterating over multidimensional arrays

The enhanced version of the for also works on multidimensional arrays. Remember, however, that in Java, multidimensional arrays consist of arrays of arrays. (For example, a two-dimensional array is an array of one-dimensional arrays.) This is important when iterating over a multidimensional array, because each iteration obtains the next array, not an individual element. Furthermore, the iteration variable in the for loop must be compatible with the type of array being obtained. For example, in the case of a two-dimensional array, the iteration variable must be a reference to a one-dimensional array. In general, when using the for-each for to iterate over an array of N dimensions, the objects obtained will be arrays of N-1 dimensions.

Intro to Chapter

A programming language uses control statements to cause the flow of execution to advance and branch based on changes to the state of a program. Java's program control statements can be put into the following categories: selection, iteration, and jump. Selection statements allow your program to choose different paths of execution based upon the outcome of an expression or the state of a variable. Iteration statements enable program execution to repeat one or more statements (that is, iteration statements form loops). Jump statements allow your program to execute in a nonlinear fashion. All of Java's control statements are examined here.

The for each version of the loop

Beginning with JDK 5, a second form of for was defined that implements a "for-each" style loop. As you may know, contemporary language theory has embraced the for-each concept, and it has become a standard feature that programmers have come to expect. A for-each style loop is designed to cycle through a collection of objects, such as an array, in strictly sequential fashion, from start to finish. Unlike some languages, such as C#, that implement a for-each loop by using the keyword foreach, Java adds the for-each capability by enhancing the for statement. The advantage of this approach is that no new keyword is required, and no preexisting code is broken. The for-each style of for is also referred to as the enhanced for loop. The general form of the for-each version of the for is shown here: for(type itr-var : collection) statement-block Here, type specifies the type and itr-var specifies the name of an iteration variable that will receive the elements from a collection, one at a time, from beginning to end. The collection being cycled through is specified by collection. There are various types of collections that can be used with the for, but the only type used in this chapter is the array. (Other types of collections that can be used with the for, such as those defined by the Collections Framework, are discussed later in this book.) With each iteration of the loop, the next element in the collection is retrieved and stored in itr-var. The loop repeats until all elements in the collection have been obtained. Because the iteration variable receives values from the collection, type must be the same as (or compatible with) the elements stored in the collection. Thus, when iterating over arrays, type must be compatible with the element type of the array.

Using break to exit a loop

By using break, you can force immediate termination of a loop, bypassing the conditional expression and any remaining code in the body of the loop. When a break statement is encountered inside a loop, the loop is terminated and program control resumes at the next statement following the loop. Here is a simple example: // Using break to exit a loop. class BreakLoop { public static void main(String args[]) { for(int i=0; i<100; i++) { if(i == 10) break; // terminate loop if i is 10 System.out.println("i: " + i); } System.out.println("Loop complete."); } } This program generates the following output: i: 0 i: 1 i: 2 i: 3 i: 4 i: 5 i: 6 i: 7 i: 8 i: 9 Loop complete. As you can see, although the for loop is designed to run from 0 to 99, the break statement causes it to terminate early, when i equals 10. The break statement can be used with any of Java's loops, including intentionally infinite loops. For example, here is the preceding program coded by use of a while loop. The output from this program is the same as just shown. // Using break to exit a while loop. class BreakLoop2 { public static void main(String args[]) { int i = 0; while(i < 100) { if(i == 10) break; // terminate loop if i is 10 System.out.println("i: " + i); i++; } System.out.println("Loop complete."); } } } When used inside a set of nested loops, the break statement will only break out of the innermost loop. For example: // Using break with nested loops. class BreakLoop3 { public static void main(String args[]) { for(int i=0; i<3; i++) { System.out.print("Pass " + i + ": "); for(int j=0; j<100; j++) { if(j == 10) break; // terminate loop if j is 10 System.out.print(j + " "); } System.out.println(); } System.out.println("Loops complete."); } } This program generates the following output: Pass 0: 0 1 2 3 4 5 6 7 8 9 Pass 1: 0 1 2 3 4 5 6 7 8 9 Pass 2: 0 1 2 3 4 5 6 7 8 9 Loops complete. As you can see, the break statement in the inner loop only causes termination of that loop. The outer loop is unaffected. Here are two other points to remember about break. First, more than one break statement may appear in a loop. However, be careful. Too many break statements have the tendency to destructure your code. Second, the break that terminates a switch statement affects only that switch statement and not any enclosing loops.

Nested loops

Like all other programming languages, Java allows loops to be nested. That is, one loop may be inside another. For example, here is a program that nests for loops: // Loops may be nested. class Nested { public static void main(String args[]) { int i, j; for(i=0; i<10; i++) { for(j=i; j<10; j++) System.out.print("."); System.out.println(); } } }

Declaring loop control variables inside the for loop

Often the variable that controls a for loop is needed only for the purposes of the loop and is not used elsewhere. When this is the case, it is possible to declare the variable inside the initialization portion of the for. For example, here is the preceding program recoded so that the loop control variable n is declared as an int inside the for: // Declare a loop control variable inside the for. class ForTick { public static void main(String args[]) { // here, n is declared inside of the for loop for(int n=10; n>0; n--) System.out.println("tick " + n); } } When you declare a variable inside a for loop, there is one important point to remember: the scope of that variable ends when the for statement does. (That is, the scope of the variable is limited to the for loop.) Outside the for loop, the variable will cease to exist. If you need to use the loop control variable elsewhere in your program, you will not be able to declare it inside the for loop. When the loop control variable will not be needed elsewhere, most Java programmers declare it inside the for.

Applying the enhanced for

Since the for-each style for can only cycle through an array sequentially, from start to finish, you might think that its use is limited, but this is not true. A large number of algorithms require exactly this mechanism. One of the most common is searching. For example, the following program uses a for loop to search an unsorted array for a value. It stops if the value is found. // Search an array using for-each style for. class Search { public static void main(String args[]) { int nums[] = { 6, 8, 3, 7, 5, 6, 1, 4 }; int val = 5; boolean found = false; // use for-each style for to search nums for val for(int x : nums) { if(x == val) { found = true; break; } } if(found) System.out.println("Value found!"); } } The for-each style for is an excellent choice in this application because searching an unsorted array involves examining each element in sequence. (Of course, if the array were sorted, a binary search could be used, which would require a different style loop.) Other types of applications that benefit from for-each style loops include computing an average, finding the minimum or maximum of a set, looking for duplicates, and so on. Although we have been using arrays in the examples in this chapter, the for-each style for is especially useful when operating on collections defined by the Collections Framework, which is described in Part II. More generally, the for can cycle through the elements of any collection of objects, as long as that collection satisfies a certain set of constraints.

Using continue

Sometimes it is useful to force an early iteration of a loop. That is, you might want to continue running the loop but stop processing the remainder of the code in its body for this particular iteration. This is, in effect, a goto just past the body of the loop, to the loop's end. The continue statement performs such an action. In while and do-while loops, a continue statement causes control to be transferred directly to the conditional expression that controls the loop. In a for loop, control goes first to the iteration portion of the for statement and then to the conditional expression. For all three loops, any intermediate code is bypassed. Here is an example program that uses continue to cause two numbers to be printed on each line: // Demonstrate continue. class Continue { public static void main(String args[]) { for(int i=0; i<10; i++) { System.out.print(i + " "); if (i%2 == 0) continue; System.out.println(""); } } } This code uses the % operator to check if i is even. If it is, the loop continues without printing a newline. Here is the output from this program: 0 1 2 3 4 5 6 7 8 9 As with the break statement, continue may specify a label to describe which enclosing loop to continue. Here is an example program that uses continue to print a triangular multiplication table for 0 through 9: // Using continue with a label. class ContinueLabel { public static void main(String args[]) { outer: for (int i=0; i<10; i++) { for(int j=0; j<10; j++) { if(j > i) { System.out.println(); continue outer; } System.out.print(" " + (i * j)); } } System.out.println(); } } The continue statement in this example terminates the loop counting j and continues with the next iteration of the loop counting i. Here is the output of this program: 0 0 1 0 2 4 0 3 6 9 0 4 8 12 16 0 5 10 15 20 25 0 6 12 18 24 30 36 0 7 14 21 28 35 42 49 0 8 16 24 32 40 48 56 64 0 9 18 27 36 45 54 63 72 81 Good uses of continue are rare. One reason is that Java provides a rich set of loop statements which fit most applications. However, for those special circumstances in which early iteration is needed, the continue statement provides a structured way to accomplish it.

Using the comma

There will be times when you will want to include more than one statement in the initialisation and iteration portions of the for loop. For example, consider the loop in the following program: class Sample { public static void main(String args[]) { int a, b; b = 4; for(a=1; a<b; a++) { System.out.println("a = " + a); System.out.println("b = " + b); b--; } } } As you can see, the loop is controlled by the interaction of two variables. Since the loop is governed by two variables, it would be useful if both could be included in the for statement, itself, instead of b being handled manually. Fortunately, Java provides a way to accomplish this. To allow two or more variables to control a for loop, Java permits you to include multiple statements in both the initialization and iteration portions of the for. Each statement is separated from the next by a comma. Using the comma, the preceding for loop can be more efficiently coded, as shown here: // Using the comma. class Comma { public static void main(String args[]) { int a, b; for(a=1, b=4; a<b; a++, b--) { System.out.println("a = " + a); System.out.println("b = " + b); } } } In this example, the initialisation portion sets the values of both a and b. The two comma- separated statements in the iteration portion are executed each time the loop repeats. The program generates the following output: a= 1 b= 4 a= 2 b= 3

Nested switch statements

You can use a switch as part of the statement sequence of an outer switch. This is called a nested switch. Since a switch statement defines its own block, no conflicts arise between the case constants in the inner switch and those in the outer switch. For example, the following fragment is perfectly valid: switch(count) { case 1: switch(target) { // nested switch case 0: System.out.println("target is zero"); break; case 1: // no conflicts with outer switch System.out.println("target is one"); break; } break; case 2: // ... Here, the case 1: statement in the inner switch does not conflict with the case 1: statement in the outer switch. The count variable is compared only with the list of cases at the outer level. If count is 1, then target is compared with the inner list cases. In summary, there are three important features of the switch statement to note: - The switch differs from the if in that switch can only test for equality, whereas if can evaluate any type of Boolean expression. That is, the switch looks only for a match between the value of the expression and one of its case constants. - No two case constants in the same switch can have identical values. Of course, a switch statement and an enclosing outer switch can have case constants in common. - A switch statement is usually more efficient than a set of nested ifs. The last point is particularly interesting because it gives insight into how the Java compiler works. When it compiles a switch statement, the Java compiler will inspect each of the case constants and create a "jump table" that it will use for selecting the path of execution depending on the value of the expression. Therefore, if you need to select among a large group of values, a switch statement will run much faster than the equivalent logic coded using a sequence of if-elses. The compiler can do this because it knows that the case constants are all the same type and simply must be compared for equality with the switch expression. The compiler has no such knowledge of a long list of if expressions.

Some for loop variations

The for loop supports a number of variations that increase its power and applicability. The reason it is so flexible is that its three parts—the initialisation, the conditional test, and the iteration—do not need to be used for only those purposes. In fact, the three sections of the for can be used for any purpose you desire. Let's look at some examples. One of the most common variations involves the conditional expression. Specifically, this expression does not need to test the loop control variable against some target value. In fact, the condition controlling the for can be any Boolean expression. For example, consider the following fragment: boolean done = false; for(int i=1; !done; i++) { // ... if(interrupted()) done = true; } In this example, the for loop continues to run until the boolean variable done is set to true. It does not test the value of i. Here is another interesting for loop variation. Either the initialisation or the iteration expression or both may be absent, as in this next program: // Parts of the for loop can be empty. class ForVar { public static void main(String args[]) { int i; boolean done = false; i = 0; for( ; !done; ) { System.out.println("i is " + i); if(i == 10) done = true; i++; } } } Here, the initialisation and iteration expressions have been moved out of the for. Thus, parts of the for are empty. While this is of no value in this simple example—indeed, it would be considered quite poor style—there can be times when this type of approach makes sense. For example, if the initial condition is set through a complex expression elsewhere in the program or if the loop control variable changes in a non-sequential manner determined by actions that occur within the body of the loop, it may be appropriate to leave these parts of the for empty. Here is one more for loop variation. You can intentionally create an infinite loop (a loop that never terminates) if you leave all three parts of the for empty. For example: for( ; ; ) { // ... } This loop will run forever because there is no condition under which it will terminate. Although there are some programs, such as operating system command processors, that require an infinite loop, most "infinite loops" are really just loops with special termination requirements. As you will soon see, there is a way to terminate a loop—even an infinite loop like the one shown—that does not make use of the normal loop conditional expression.

switch

The switch statement is Java's multiway branch statement. It provides an easy way to dispatch execution to different parts of your code based on the value of an expression. As such, it often provides a better alternative than a large series of if-else-if statements. Here is the general form of a switch statement: switch (expression) { case value1: // statement sequence break; case value2: // statement sequence break; . . . case valueN: // statement sequence break; default: // default statement sequence } For versions of Java prior to JDK 7, expression must be of type byte, short, int, char, or an enumeration. (Enumerations are described in Chapter 12.) Beginning with JDK 7, expression can also be of type String. Each value specified in the case statements must be a unique constant expression (such as a literal value). Duplicate case values are not allowed. The type of each value must be compatible with the type of expression. The switch statement works like this: The value of the expression is compared with each of the values in the case statements. If a match is found, the code sequence following that case statement is executed. If none of the constants matches the value of the expression, then the default statement is executed. However, the default statement is optional. If no case matches and no default is present, then no further action is taken. The break statement is used inside the switch to terminate a statement sequence. When a break statement is encountered, execution branches to the first line of code that follows the entire switch statement. This has the effect of "jumping out" of the switch.

return

return The last control statement is return. The return statement is used to explicitly return from a method. That is, it causes program control to transfer back to the caller of the method. As such, it is categorized as a jump statement. Although a full discussion of return must wait until methods are discussed in Chapter 6, a brief look at return is presented here. At any time in a method, the return statement can be used to cause execution to branch back to the caller of the method. Thus, the return statement immediately terminates the method in which it is executed. The following example illustrates this point. Here, return causes execution to return to the Java run-time system, since it is the run-time system that calls main( ): // Demonstrate return. class Return { public static void main(String args[]) { boolean t = true; System.out.println("Before the return."); if(t) return; // return to caller System.out.println("This won't execute."); } } The output from this program is shown here: Before the return. As you can see, the final println( ) statement is not executed. As soon as return is executed, control passes back to the caller. One last point: In the preceding program, the if(t) statement is necessary. Without it, the Java compiler would flag an "unreachable code" error because the compiler would know that the last println( ) statement would never be executed. To prevent this error, the if statement is used here to trick the compiler for the sake of this demonstration.


Ensembles d'études connexes

Module 11, 12, 13, and 14 Assessment Questions

View Set

อิทอิส Chapter 2 Q:1-40

View Set

CCNA 4 chapter 8 Network Troubleshooting

View Set

FBLA Banking and Financial Systems

View Set

084 Social Studies (Secondary) - General 2.0

View Set

chpt 13 psychology test study guide

View Set

Chapter 13: Abstract Classes and Interfaces

View Set