Flow control Exceptions and Assertions in Java

flow control for exception handling,control flow in exceptions,using exceptions for flow control java,exceptions control program flow pdf free download
OliviaCutts Profile Pic
OliviaCutts,France,Teacher
Published Date:01-08-2017
Your Website URL(Optional)
Comment
Color profile: Generic CMYK printer profile CertPrs8(SUN) / Sun Certified Programmer & Developer for Java 2 Study Guide / Sierra / 222684-6 / Chapter 4 Composite Default screen Blind Folio 4:1 4 Flow Control, Exceptions, and Assertions CERTIFICATION OBJECTIVES • Writing Code Using if and switch Statements  Writing Code Using Loops  Handling Exceptions  Working with the Assertion Mechanism ✓ Two-Minute Drill Q&A Self Test P:\010Comp\CertPrs8\684-6\ch04.vp Wednesday, November 13, 2002 5:18:06 PMColor profile: Generic CMYK printer profile CertPrs8(SUN) CertPrs8(SUN) / Sun Certified Programmer & Developer for Java 2 Study Guide / Sierra / 222684-6 / Chapter / Sun Certified Programmer & Developer for Java 2 Study Guide / Sierra / 222684-6 / Chapter 4 4 Composite Default screen Chapter 4: Flow Control, Exceptions, and Assertions 2 an you imagine trying to write code using a language that didn’t give you a way to execute statements conditionally? In other words, a language that didn’t let you say, C“If this thing over here is true, then I want this thing to happen; otherwise, do this other thing instead.” Flow control is a key part of most any useful programming language, and Java offers several ways to do it. Some, like if statements and for loops, are common to most languages. But Java also throws in a couple flow control features you might not have used before—exceptions and assertions. The if statement and the switch statement are types of conditional/decision controls that allow your program to perform differently at a “fork in the road,” depending on the result of a logical test. Java also provides three different looping constructs—for, while, anddo-while—so you can execute the same code over and over again depending on some condition being true. Exceptions give you a clean, simple way to organize code that deals with problems that might crop up at runtime. Finally, the assertion mechanism, added to the language with version 1.4, gives you a way to do debugging checks on conditions you expect to smoke out while developing, when you don’t necessarily need or want the runtime overhead associated with exception handling. With these tools, you can build a robust program that can handle any logical situation with grace. Expect to see a wide range of questions on the exam that include flow control as part of the question code, even on questions that aren’t testing your knowledge of flow control. CERTIFICATION OBJECTIVE Writing Code Using if and switch Statements (Exam Objective 2.1) Write code using if and switch statements and identify legal argument types for these statements. The if and switch statements are commonly referred to as decision statements. When you use decision statements in your program, you’re asking the program to evaluate a given expression to determine which course of action to take. We’ll look at the if statement first. P:\010Comp\CertPrs8\684-6\ch04.vp Wednesday, November 13, 2002 5:18:06 PMColor profile: Generic CMYK printer profile CertPrs8(SUN) CertPrs8(SUN) / Sun Certified Programmer & Developer for Java 2 Study Guide / Sierra / 222684-6 / Chapter / Sun Certified Programmer & Developer for Java 2 Study Guide / Sierra / 222684-6 / Chapter 4 4 Composite Default screen Writing Code Using if and switch Statements (Exam Objective 2.1) 3 if-else Branching The basic format of anif statement is as follows: if (booleanExpression) System.out.println("Inside if statement"); The expression in parentheses must evaluate to a booleantrue orfalse result. Typically you’re testing something to see if it’s true, and then running a code block (one or more statements) if it is true, and (optionally) another block of code if it isn’t. We consider it good practice to enclose the blocks within curly braces, even if there’s only one statement in the block. The following code demonstrates a legalif statement: if (x 3) System.out.println("x is greater than 3"); else System.out.println("x is not greater than 3"); Theelse block is optional, so you can also use the following: if (x 3) y = 2; z += 8; a = y + x; The preceding code will assign 2 to y if the test succeeds (meaning x really is greater than 3), but the other two lines will execute regardless. Even the curly braces are optional if you have only one statement to execute within the body of the conditional block. The following code example is legal (although not recommended for readability): if (x 3) y = 2; z += 8; a = y + x; Be careful with code like this, because you might think it should read as, “If x is greater than 3, then set y to 2, z to z + 8, and a to y + x.” But the last two lines are P:\010Comp\CertPrs8\684-6\ch04.vp Wednesday, November 13, 2002 5:18:06 PMColor profile: Generic CMYK printer profile CertPrs8(SUN) / Sun Certified Programmer & Developer for Java 2 Study Guide / Sierra / 222684-6 / Chapter 4 Composite Default screen Chapter 4: Flow Control, Exceptions, and Assertions 4 going to execute no matter what They aren’t part of the conditional flow. You might find it even more misleading if the code were indented as follows: if (x 3) y = 2; z += 8; a = y + x; You might have a need to nest if-else statements (although, again, not recommended for readability, so nested if tests should be kept to a minimum). You can set up an if-else statement to test for multiple conditions. The following example uses two conditions so that if the first test succeeds, we want to perform a second test before deciding what to do: if (price 300) buyProduct(); else if (price 400) getApproval(); else dontBuyProduct(); Sometimes you can have a problem figuring out which if your else goes to, as follows: if (exam.done()) if (exam.getScore() 0.61) System.out.println("Try again."); else System.out.println("Java master"); // Which if does this belong to? We intentionally left out the indenting in this piece of code so it doesn’t give clues as to which if statement the else belongs to. Did you figure it out? Java law decrees that an else clause belongs to the innermost if statement to which it might possibly belong (in other words, the closest precedingif that doesn’t have anelse). In the case of the preceding example, theelse belongs to the secondif statement in the listing. With proper indenting, it would look like this: if (exam.done()) if (exam.getScore() 0.61) System.out.println("Try again."); P:\010Comp\CertPrs8\684-6\ch04.vp Wednesday, November 13, 2002 5:18:06 PMColor profile: Generic CMYK printer profile CertPrs8(SUN) / Sun Certified Programmer & Developer for Java 2 Study Guide / Sierra / 222684-6 / Chapter 4 Composite Default screen Writing Code Using if and switch Statements (Exam Objective 2.1) 5 else System.out.println("Java master"); // Which if does this belong to? Following our coding conventions by using curly braces, it would be even easier to read: if (exam.done()) if (exam.getScore() 0.61) System.out.println("Try again."); else System.out.println("Java master"); // Which if does this belong to? Don’t be getting your hopes up about the exam questions being all nice and indented properly, however. Some exam takers even have a slogan for the way questions are presented on the exam: anything that can be made more confusing, will be. Be prepared for questions that not only fail to indent nicely, but intentionally indent in a misleading way: Pay close attention for misdirection like the following example: if (exam.done()) if (exam.getScore() 0.61) System.out.println(“Try again.”); else System.out.println(“Java master”); // Hmmmmm… now where does it belong? Of course, the preceding code is exactly the same as the previous two examples, except for the way it looks. Legal Arguments for if Statements if statements can test against only a boolean. Any expression that resolves down to a boolean is fine, but some of the expressions can be complex, like the following, int y = 5; int x = 2; if ((((x 3) && (y 2)) doStuff())) System.out.print("true"); P:\010Comp\CertPrs8\684-6\ch04.vp Wednesday, November 13, 2002 5:18:06 PMColor profile: Generic CMYK printer profile CertPrs8(SUN) / Sun Certified Programmer & Developer for Java 2 Study Guide / Sierra / 222684-6 / Chapter 4 Composite Default screen Chapter 4: Flow Control, Exceptions, and Assertions 6 which prints true You can read the preceding code as, “If both (x 3) and (y 2) are true, or if the result ofdoStuff() is true, then print “true.” So basically, if justdoStuff() alone is true, we’ll still get “true.” IfdoStuff() is false, though, then both (x 3) and (y 2) will have to be true in order to print “true.” The preceding code is even more complex if you leave off one set of parentheses as follows, int y = 5; int x = 2; if (((x 3) && (y 2) doStuff())) System.out.print("true"); which now prints…nothing Because the preceding code (with one less set of parentheses) evaluates as though you were saying, “If (x3)is true, and either (y2) or the result ofdoStuff() is true, then print “true.” So if (x 3) is not true, no point in looking at the rest of the expression.” Because of the short-circuit && and the fact that at runtime the expression is evaluated as though there were parentheses around((y 2) doStuff()), it reads as though both the test before the && (x3) and then the rest of the expression after the&& (y2 doStuff()) must be true. Remember that the only legal argument to an if test is a boolean. Table 4-1 lists illegal arguments that might look tempting, compared with a modification to make each argument legal. One common mistake programmers make (and that can be difficult to spot), is assigning a boolean variable when you meant to test a boolean variable. Look out for code like the following: boolean boo = false; if (boo = true) You might think one of three things: 1. The code compiles and runs fine, and the if test fails because boo is false. 2. The code won’t compile because you’re using an assignment (=) rather than an equality test (==). 3. The code compiles and runs fine and the if test succeeds because boo is set to true (rather than tested for true) in the if argument P:\010Comp\CertPrs8\684-6\ch04.vp Wednesday, November 13, 2002 5:18:07 PMColor profile: Generic CMYK printer profile CertPrs8(SUN) / Sun Certified Programmer & Developer for Java 2 Study Guide / Sierra / 222684-6 / Chapter 4 Composite Default screen Writing Code Using if and switch Statements (Exam Objective 2.1) 7 Well, number 3 is correct. Pointless, but correct. Given that the result of any assignment is the value of the variable after the assignment, the expression (boo = true) has a result of true. Hence, the if test succeeds. But the only variable that can be assigned (rather than tested against something else) is a boolean; all other assignments will result in something nonboolean, so they’re not legal, as in the following: int x = 3; if (x = 5) // Won’t compile because x is not a boolean Because if tests require boolean expressions, you need to be really solid on both logical operators and if test syntax and semantics. switch Statements Another way to simulate the use of multiple if statements is with the switch statement. Take a look at the following if-else code, and notice how confusing it can be to have nested if tests, even just a few levels deep: int x = 3; if(x == 1) System.out.println("x equals 1"); else if(x == 2) System.out.println("x equals 2"); else if(x == 3) System.out.println("x equals 3"); else System.out.println("No idea what x is"); TABLE 4-1 Illegal Arguments to if Legal Arguments to if Illegal and Legal int x = 1; int x = 1; if (x) if (x == 1) Arguments to if if (0) if (false) if (x = 6) if (x == 6) P:\010Comp\CertPrs8\684-6\ch04.vp Wednesday, November 13, 2002 5:18:07 PMColor profile: Generic CMYK printer profile CertPrs8(SUN) / Sun Certified Programmer & Developer for Java 2 Study Guide / Sierra / 222684-6 / Chapter 4 Composite Default screen Chapter 4: Flow Control, Exceptions, and Assertions 8 Now let’s see the same functionality represented in a switch construct: int x = 3; switch (x) case 1: System.out.println("x is equal to 1"); break; case 2: System.out.println("x is equal to 2"); break; case 3: System.out.println("x is equal to 3"); break; default: System.out.println("Still no idea what x is"); Legal Arguments to switch and case The only type that a switch can evaluate is the primitiveint That means only variables and valuables that can be automatically promoted (in other words, implicitly cast) to anint are acceptable. So you can switch on any of the following, but nothing else: byte short char int You won’t be able to compile if you use anything else, including the remaining numeric types oflong,float, anddouble. The only argument a case can evaluate is one of the same type as switch can use, with one additional—and big—constraint: the case argument must be final The case argument has to be resolved at compile time, so that means you can use only a literal or final variable. Also, the switch can only check for equality. This means that the other relational operators such as greater than are rendered unusable in a case. The following is an example of a valid expression using a method invocation in a switch statement. Note that for this code to be legal, the method being invoked on the object reference must return a value compatible with anint. String s = "xyz"; switch (s.length()) case 1: P:\010Comp\CertPrs8\684-6\ch04.vp Wednesday, November 13, 2002 5:18:07 PMColor profile: Generic CMYK printer profile CertPrs8(SUN) / Sun Certified Programmer & Developer for Java 2 Study Guide / Sierra / 222684-6 / Chapter 4 Composite Default screen Writing Code Using if and switch Statements (Exam Objective 2.1) 9 System.out.println("length is one"); break; case 2: System.out.println("length is two"); break; case 3: System.out.println("length is three"); break; default: System.out.println("no match"); The following example uses final variables in a case statement. Note that if the final keyword is omitted, this code will not compile. final int one = 1; final int two = 2; int x = 1; switch (x) case one: System.out.println("one"); break; case two: System.out.println("two"); break; One other rule you might not expect involves the question, “What happens if I switch on a variable smaller than anint?” Look at the followingswitch example: byte g = 2; switch(g) case 23: case 128: This code won’t compile. Although the switch argument is legal—abyte is implicitly cast to anint—the second case argument (128) is too large for abyte, and the compiler knows it Attempting to compile the preceding example gives you an error: Test.java:6: possible loss of precision found : int required: byte case 129: P:\010Comp\CertPrs8\684-6\ch04.vp Wednesday, November 13, 2002 5:18:07 PMColor profile: Generic CMYK printer profile CertPrs8(SUN) / Sun Certified Programmer & Developer for Java 2 Study Guide / Sierra / 222684-6 / Chapter 4 Composite Default screen Chapter 4: Flow Control, Exceptions, and Assertions 10 It’s also illegal to have more than one case label using the same value. For example, the following block of code won’t compile because it uses two cases with the same value of 80: int temp = 90; switch(temp) case 80 : System.out.println("80"); break; case 80 : System.out.println("80"); break; case 90: System.out.println("90"); break; default: System.out.println("default"); Look for any violation of the rules for switch and case arguments. For example, you might find illegal examples like the following three snippets: Integer in = new Integer(4); switch (in) ================== switch(x) case 0 y = 7; ================== switch(x) 0: 1: In the first example, you can’t switch on an Integer object, only anint primitive. In the second example, the case uses a curly brace and omits the colon. The third example omits the keywordcase. P:\010Comp\CertPrs8\684-6\ch04.vp Wednesday, November 13, 2002 5:18:07 PMColor profile: Generic CMYK printer profile CertPrs8(SUN) / Sun Certified Programmer & Developer for Java 2 Study Guide / Sierra / 222684-6 / Chapter 4 Composite Default screen Writing Code Using if and switch Statements (Exam Objective 2.1) 11 Default, Break, and Fall-Through in switch Blocks When the program encounters the keywordbreak during the execution of a switch statement, execution will immediately move out of theswitch block to the next statement after theswitch. If break is omitted, the program just keeps executing the different case blocks until either abreak is found or the switch statement ends. Examine the following code: int x = 1; switch(x) case 1: System.out.println("x is one"); case 2: System.out.println("x is two"); case 3: System.out.println("x is three"); System.out.println("out of the switch"); The code will print the following: x is one x is two x is three out of the switch This combination occurs because the code didn’t hit a break statement; thus, execution just kept dropping down through eachcase until the end. This dropping down is actually called “fall through,” because of the way execution falls from one case to the next. Think of the matchingcase as simply your entry point into the switch block In other words, you must not think of it as, “Find the matching case, execute just that code, and get out.” That’s not how it works. If you do want that “just the matching code” behavior, you’ll insert a break into eachcase as follows: int x = 1; switch(x) case 1: System.out.println("x is one"); break; case 2: System.out.println("x is two"); break; case 3: System.out.println("x is two"); P:\010Comp\CertPrs8\684-6\ch04.vp Wednesday, November 13, 2002 5:18:07 PMColor profile: Generic CMYK printer profile CertPrs8(SUN) / Sun Certified Programmer & Developer for Java 2 Study Guide / Sierra / 222684-6 / Chapter 4 Composite Default screen Chapter 4: Flow Control, Exceptions, and Assertions 12 break; System.out.println("out of the switch"); Running the preceding code, now that we’ve added the break statements, will print x is one out of the switch and that’s it. We entered into the switch block atcase 1. Because it matched the switch() argument, we got theprintln statement, then hit thebreak and jumped to the end of the switch. Another way to think of this fall-through logic is shown in the following code: int x = someNumberBetweenOneAndTen; switch (x) case 2: case 4: case 6: case 8: case 10: System.out.println("x is an even number"); break; This switch statement will print “x is an even number” or nothing, depending on whether the number is between one and ten and is odd or even. For example, if x is 4, execution will begin atcase 4, but then fall down through 6, 8, and 10, where it prints and then breaks. Thebreak atcase 10, by the way, is not needed; we’re already at the end of the switch anyway. The Default Case What if, using the preceding code, you wanted to print “x is an odd number” if none of the cases (the even numbers) matched? You couldn’t put it after the switch statement, or even as the last case in the switch, because in both of those situations it would always print “x is an odd number.” To get this behavior, you’ll use the default keyword. (By the way, if you’ve wondered why there is adefault keyword even though we don’t use a modifier for default access control, now you’ll P:\010Comp\CertPrs8\684-6\ch04.vp Wednesday, November 13, 2002 5:18:08 PMColor profile: Generic CMYK printer profile CertPrs8(SUN) / Sun Certified Programmer & Developer for Java 2 Study Guide / Sierra / 222684-6 / Chapter 4 Composite Default screen Writing Code Using if and switch Statements (Exam Objective 2.1) 13 see that thedefault keyword is used for a completely different purpose.) The only change we need to make is to add the default case to the preceding code: int x = someNumberBetweenOneAndTen; switch (x) case 2: case 4: case 6: case 8: case 10: System.out.println("x is an even number"); break; default: System.out.println("x is an odd number"); The default case doesn’t have to come at the end of the switch. Look for it in strange places such as the following: int x = 2; switch (x) case 2: System.out.println(“2”); default: System.out.println(“default”); case 3: System.out.println(“3”); case 4: System.out.println(“4”); Running the preceding code prints 2 default 3 4 and if we modify it so that the only match is the default case: int x = 7; switch (x) case 2: System.out.println(“2”); default: System.out.println(“default”); case 3: System.out.println(“3”); case 4: System.out.println(“4”); P:\010Comp\CertPrs8\684-6\ch04.vp Wednesday, November 13, 2002 5:18:08 PMColor profile: Generic CMYK printer profile CertPrs8(SUN) / Sun Certified Programmer & Developer for Java 2 Study Guide / Sierra / 222684-6 / Chapter 4 Composite Default screen Chapter 4: Flow Control, Exceptions, and Assertions 14 Running the preceding code prints default 3 4 The rule to remember isdefault works just like any other case for fall-through EXERCISE 4-1 Creating a switch-case Statement Try creating a switch-case statement using achar value as the case. Include a default behavior if none of thechar values match. 1. Make sure achar variable is declared before the switch statement. 2. Each case statement should be followed by abreak. 3. Thedefault value can be located at the end, middle, or top. CERTIFICATION OBJECTIVE Writing Code Using Loops (Exam Objective 2.2) Write code using all forms of loops including labeled and unlabeled, use of break and continue, and state the values taken by loop counter variables during and after loop execution. Java loops come in three flavors: while, do-while, 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. P:\010Comp\CertPrs8\684-6\ch04.vp Wednesday, November 13, 2002 5:18:08 PMColor profile: Generic CMYK printer profile CertPrs8(SUN) / Sun Certified Programmer & Developer for Java 2 Study Guide / Sierra / 222684-6 / Chapter 4 Composite Default screen Writing Code Using Loops (Exam Objective 2.2) 15 Using while Loops The while loop is good for scenarios where you don’t know how many times block or statement should repeat, but you want it to continue as long as some condition is true. A while statement looks like this: 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. 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) 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 body of the while loop will only execute if the condition results in a true value. Once inside the loop, the loop body will repeat until the condition is no longer met and 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. 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 P:\010Comp\CertPrs8\684-6\ch04.vp Wednesday, November 13, 2002 5:18:08 PMColor profile: Generic CMYK printer profile CertPrs8(SUN) / Sun Certified Programmer & Developer for Java 2 Study Guide / Sierra / 222684-6 / Chapter 4 Composite Default screen Chapter 4: Flow Control, Exceptions, and Assertions 16 Although the test variable x is incremented within the while loop body, the program will never see it. This is in contrast to the do-while loop that executes the loop body once, and then does the first test. Using do-while Loops The following shows ado-while statement in action: do System.out.println("Inside loop"); while(false); TheSystem.out.println() statement will print once, even though the expression evaluates to false. The do-while 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. As with if tests, look for while loops (and the while test in a do-while loop) with an expression that does not resolve to a boolean. Take a look at the following examples of legal and illegalwhile expressions: intx=1; while (x) // Won’t compile; x is not a boolean while (x = 5)// Won’t compile; resolves to 5 (result of assignment) while (x == 5) // Legal, equality test while (true)// Legal Using for Loops 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 P:\010Comp\CertPrs8\684-6\ch04.vp Wednesday, November 13, 2002 5:18:08 PMColor profile: Generic CMYK printer profile CertPrs8(SUN) / Sun Certified Programmer & Developer for Java 2 Study Guide / Sierra / 222684-6 / Chapter 4 Composite Default screen Writing Code Using Loops (Exam Objective 2.2) 17 Each of the three for declaration parts is separated by a semicolon. 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 typical syntax of the loop. for (/Initialization/ ; /Condition/ ; / Iteration /) / loop body / for (int i = 0; i10; i++) System.out.println("i is " + i); 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 thefor 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 Test.java:19: cannot resolve symbol symbol : variable x location: class Test System.out.println(x); P:\010Comp\CertPrs8\684-6\ch04.vp Wednesday, November 13, 2002 5:18:08 PMColor profile: Generic CMYK printer profile CertPrs8(SUN) / Sun Certified Programmer & Developer for Java 2 Study Guide / Sierra / 222684-6 / Chapter 4 Composite Default screen Chapter 4: Flow Control, Exceptions, and Assertions 18 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. Iteration Expression After each execution of the body of the for loop, the iteration expression is executed. This part 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 here 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 thefor loop and continues on. Keep in mind that this iteration expression is always the last thing that happens So although the body may never execute again, the iteration expression always runs at the end of the loop block, as long as no P:\010Comp\CertPrs8\684-6\ch04.vp Wednesday, November 13, 2002 5:18:08 PMColor profile: Generic CMYK printer profile CertPrs8(SUN) / Sun Certified Programmer & Developer for Java 2 Study Guide / Sierra / 222684-6 / Chapter 4 Composite Default screen Writing Code Using Loops (Exam Objective 2.2) 19 other code within the loop causes execution to leave the loop. For example, abreak, return, exception, orSystem.exit() 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 areturn 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 4-2 lists the causes and results of abrupt loop termination. for Loop Issues None of the three sections of thefor 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 it will act like an endless loop. For the exam, it’s important to know that with the absence of the TABLE 4-2 Causes of Early Loop Termination Code in Loop What Happens break Execution jumps immediately to the first statement after the for loop. return Execution immediately jumps back to the calling method. System.exit() All program execution stops; the VM shuts down. P:\010Comp\CertPrs8\684-6\ch04.vp Wednesday, November 13, 2002 5:18:09 PMColor profile: Generic CMYK printer profile CertPrs8(SUN) / Sun Certified Programmer & Developer for Java 2 Study Guide / Sierra / 222684-6 / Chapter 4 Composite Default screen Chapter 4: Flow Control, Exceptions, and Assertions 20 initialization and increment sections, the loop will act like a while loop. The following example demonstrates how this is accomplished: int i = 0; for (;i10;) 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; (i10) && (j10); i++, j++) System.out.println("i is " + i + "j is " +j); 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 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; P:\010Comp\CertPrs8\684-6\ch04.vp Wednesday, November 13, 2002 5:18:09 PM

Advise: Why You Wasting Money in Costly SEO Tools, Use World's Best Free SEO Tool Ubersuggest.