Control Flow Statements

Team-Fly

So far we have spent most of this chapter talking about variables, data types, arrays, and literals. To make Java programs useful, though, we need ways to control the logic flow of the software. Flow control can basically be broken up into four areas:

  • Decision making

  • Looping

  • Exception handling

  • Miscellaneous

Decision Making

Decision making in Java is usually controlled with the if-else or switch commands. The switch command is basically a fancy if-else statement, so we start our explanation with the if-else command.

The basic syntax of the if-else is as follows:

if (expression) statement;

In this simple case, if the expression evaluates to true, then the statement is executed. The statement can be a series of lines surrounded by curly brackets ({}).

If (expression) {     statement 1;     statement 2;     . . . }
Note 

The curly brackets {} can be used anywhere in the Java language and indicate that all of the statements between the brackets are to be treated as one statement.

The else portion of the if-else statement is executed if the expression associated with the previous if is evaluated as false.

If (expression1) { . . .statements executed if expression1 is true; . . ._} else if (expression2)_{ . . . statements executed if expression1 is false and expression2 is true . . . } else { . . . statements executed if expression1 and expression2 are both false. . . . }

As mentioned previously, the switch statement is just a derivation of the if-else statement. Using the switch statement makes your code easier to read because you do not have to code a series of else statements. A simple example of the same logic coded with both an if and a switch follows.

// If Statement to print first three months of the year  if month == 1     System.out.println("January"); else if month == 2     System.out.println("February"); else if month == 3     System.out.println("March"); Endif // Same logic, but using the switch statement instead switch (month) {     case 1: System.out.println("January");     case 2: System.out.println("February");     case 3: System.out.println("March"); }

In a switch statement, the value right after the switch statement is evaluated against each value in each case statement. If the values are equal, then all of the following statements are executed until the end of the case statement or until the Java break command is encountered.

The break command terminates the switch and moves execution to the line following the switch statement. Curly brackets are not required when using multiple statements in each case statement. You can also use the term default in the last case statement to handle any expression that does not match one of the previous case statements. The following example demonstrates a slightly more complex switch statement.

Switch (month) {     case 2:         if ((year % 4 == 0) && ((year % 100 != 0) ||         ((year % 400) == 0))         System.out.println("Number of days = 29");         else             System.out.println("Number of days = 28");         break;     case 4:     case 6:     case 9:     case 11:         System.out.println("Number of days = 30");         break;     default: System.out.println("Number of days = 31"); }

Notice that if the month is June, the program still prints that the number of days is equal to 30 because all statements are executed until the next break statement is encountered.

Note 

C programmers should take note that the switch command in Java is not quite the same as it is in C. In Java, the switch command evaluates only simple integer conditions, not more complicated data types like floats or strings.

Looping

Java has three different types of looping commands: do-while, while-do, and for.

The do-while and the while-do commands work in a similar fashion-the only difference is when the condition of the loop is evaluated. With the while-do, the expression is evaluated first, and then the statement block is executed if the expression is true. The do-while evaluates the expression block after the statement block has executed, and therefore the statement block is always executed at least once. The following is an example of a while-do loop:

int I = 4; while(i < 4) { System.out.println(i); i = i + 1; }

The preceding loop prints out nothing because the value of i fails the test i < 4. Consider the following do-while loop:

int i = 4; do { System.out.println(i); i = i + 1; }while (i < 4)

In the preceding example, the program prints out the value 4 because the statements in the loop are executed before the loop condition is processed.

The other type of loop condition in Java is the for loop, which has the following general syntax:

For(initialization code, termination evaluation, increment code) { statements }

In the initialization code, you can both initialize and declare variables before the loop is executed. Variables that are declared here can be used inside the loop only and cease to exist when the loop has finished. Multiple variables must be separated by commas. The evaluation section of the for loop is tested once per pass and works like the while-do loop. The increment code is a statement (or a series of statements separated by commas) that is executed after each execution of the loop and before the evaluation for the loop is performed. Some examples of for loops follow:

// A simple FOR loop for(int i = 1; i < 4; ++i) system.out.println(i); // a bit more complex example int i; for(i= 1, int j = 3; i < j; ++ i) {_    System.out.println(i); }

Other Ways to Control Program Flow

The break statement, which can be used in any loop, causes the loop to stop processing immediately and continue the program with the statement right after the loop block. For a more elaborate form of the break command, you can break out of a loop to a specific piece in the code. This technique puts a label on a piece of Java code before the loop. When you use a label with the break command, the label must be outside the loop that contains the break, as shown in the following example:

Caution 

One of the most common programming mistakes is the misplaced semicolon (;), especially in if and loop statements. Look at the following code segment and take a guess at the output.

for(int i = 1; i < 4; ++i);             System.out.println(i);
Caution 

If you guessed that the code would print '1 2 3,' you are wrong! The semicolon after the for statement terminates the for loop, and the System.out.println statement is executed as a simple Java statement; the output is '4.' This mistake is easy to make because in Java (and in C) you get in the habit of putting the semicolon behind every line. Use caution whenever you build an if or a loop statement-make sure that the semicolons are placed correctly!

 . . . testLabel:     If (userInput < 0)      {             System.out.println("invalid userInput");             UserInput = 1;        }    for(int i = 1; i< 10; ++i)     {             if (userInput < 0) break testLabel;             result = userInput / i;             System.out.println(result);     } . . .

Another way to control program flow in loop processing is to use the Java keyword continue. The continue statement stops processing the current loop iteration and starts processing the next loop pass from the top of the loop logic, as shown in the following code example:

. . . for( I = -5 ; I < 5; ++I ) {     if ( I == 0) continue;     result = 1 / I;     System.out.println(result); } . . .

One other way to control program flow is with the Java return statement. The return statement terminates processing of the current method and returns the program call to the calling method. An addition to the return statement can be the return value of the method. In Chapter 8, 'Objects, Classes, and Interfaces,' we discuss how methods can return values in detail, but for now you can think of a method as being declared as a type of variable. If a method is declared as a type void, there is no return value. A method could also be declared as a type int and, in this case, would be expected to return an integer value. When you use the return keyword in a method, it must return a variable with the same type declaration as the method from which it is called.

Exception Handling

An exception can be defined as an event that causes a change in the normal flow of a program. Examples of exceptions are a file not being found, or unexpected input from a user. When an exception occurs in a program, the system tries to find a way to handle this event by going through the methods until it finds one that is set up to handle the exception that has occurred. The methods that handle exceptions are called exception handlers. When an exception is raised, it is said to be 'thrown,' and when an appropriate method is found, it is said to have 'caught' the exception.

The general format for Java code that is set up to handle exceptions is as follows:

. . . try{ statements }catch (exception1 variable) statement to handle exception;  catch (exception2 variable) statement to handle exception; . . .

As you can see, exception handling is achieved by grouping some statements in a try block and then handling any exceptions that may occur in this block with one or more catch blocks. Inheritance also takes part in the process of exception handling in that the first catch block that matches a generated exception is executed, and any other catch blocks that may exist are ignored.

Note 

The exception process in Java is similar to the ABAP exception process of calling function modules. In a function module, you raise an exception, and then the calling program handles the exception through the sy-subrc return code. The difference is that in Java the exception is an event and does not automatically stop processing the current method, as the raise command in ABAP does.

Exceptions in Java are really objects of the Java class throwable. This class has two subclasses: error and exception. The error subclass is used for internal errors to the Java run-time environment, whereas the exception subclass is used for all other error types, such as I/O exceptions or class not found. To raise a generic exception in your program, you can simply create a new instance of the exception class and use the Java command throws.

 . . . // Example #1 Exception() myException = new Exception("Descriptive Text"); Throw myException; return;   // Usually added // Example # 2 throws new Exception("Descriptive Text here"); return;   // Usually added . . .

To catch a generic exception like the one generated in the preceding example, you would use a piece of code like this:

. . . Try{  // Statements that could generate the Exception }catch(Exception e){ System.out.println(e.string); } . . .

The one other Java keyword associated with the try block is the finally block. The finally block is used like a catch block, as shown in the following example, and is executed regardless of how the try block is finished (exception or not).

. . . try{ statements }catch (exception1 variable) statement to handle exception;  catch (exception2 variable) statement to handle exception;  finally  statement to process regardless of the try block finishes . . .

A full explanation of the declaration, creation, and use of exceptions is beyond the scope of this book. This section exists to make you aware of the concept and to explain how it can and should be used to handle unexpected events in your programs. The following sample program ties together all the exception-related topics discussed in this chapter. The program reads in a file and prints the value of each byte to the screen.

 public class Jsap0702 {     public static void main (String[] args)     {         FileInputStream fStr;         Boolean endOfFile = false;         Int    input;         try{             fStr = new FileInputStream("C:\test.txt");              while (!endOfFile)             {                 byte = fstr.read();                 System.out.print(byte + " ");                 If ( byte == -1 ) endOfFile = true;             }             fstr.close();         }catch (IOException e){          System.out.println("I/O error encounter:" + e.toString());         }     } }

One final note about exceptions. You should write your code to catch errors that will prevent your program from executing, such as an end of file, but you should not use exception processing to handle events that you know will take place. Exception processing is very resource intensive and should not be used for things like verifying user input, which can easily be checked by other means.


Team-Fly


Java & BAPI Technology for SAP
Java & BAPI Technology for SAP
ISBN: 761523057
EAN: N/A
Year: 1998
Pages: 199

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