Transfer of Control Statements


Transfer of control statements moves the point of execution in your program to another location. They are used to exit from loops and other control structures, to return to the top of a loop, or to return from a method.

break Statements

We encountered the break statement in our discussion of switch statements. A break statement is used to exit the current loop or other flow control structure. The program execution is sent to the next statement following the control structure. By default, a break statement inside a nested loop will exit only the current loop, not the entire loop structure. You can add a label after a break statement to break out of a specified labeled block of code.

Example: Breaking Out of an Outer Loop

In this example, two for loops are used to search a 2-D array of data for a negative value. If a negative value is found, its location is noted and the loop exits. We want to exit both the inner and outer loops if a negative value is found. To do this, we label the outer for loop "outer" and use a labeled break statement. If a simple break statement had been used (without the label) only the inner loop would have been exited. The outer loop would continue normally.

 public class BreakDemo {   public static void main(String args[]) {     double data[][] = { {4.1, 3.2, 1.1},                         {-1.3, 2.4, 6.7},                         {7.7, 0.3, 9.8} };     outer: for(int i=0; i<3; ++i) {       for(int j=0; j<3; ++j) {         System.out.println("i= " + i + " j= " + j);         if (data[i][j] < 0.0) {            System.out.println("negative value at" +                  " [" + i + "][" + j + "]");            break outer;         }       }     }   } } 

Output ”

 i=0 j=0 i=0 j=1 i=0 j=2 i=1 j=0 negative value at [1][0] 

continue Statements

A continue statement causes program execution to return to the top of the current loop, bypassing any code that may be defined below the continue statement. Similar to the break statement, a continue statement can provide a label to return to the top of a labeled loop. The continue statement is an example of a redundancy within Java. Anything you can do with a continue statement you can also do with an if-else statement. Because of this, you will rarely see or use continue statements.

return Statements

The return statement is used to return from a method. It transfers program control to the executable statement following the method call. The return keyword can be used by itself or it can precede a value that will be returned. More details on return statements are provided in Chapter 9.



Technical Java. Applications for Science and Engineering
Technical Java: Applications for Science and Engineering
ISBN: 0131018159
EAN: 2147483647
Year: 2003
Pages: 281
Authors: Grant Palmer

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