Iteration Statements


Selection Statements

There are three types of Java selection statements: if, if/else, and switch. The use of each of these statements is covered in detail in this section.

if Statement

The if statement is used to conditionally execute a block of code based on the results of a conditional expression evaluation. Figure 7-1 graphically shows what happens during the processing of an if statement.

image from book
Figure 7-1: if Statement Execution Diagram

If the conditional expression contained within the parentheses evaluates to true then the body of the if statement executes. If the expression evaluates to false then the statements contained within the if statement body are bypassed and processing continues on to the next statement following the if statement.

Example 7.1 shows an if statement being used in a simple program that reads two integer values from the command line and compares their values. Figure 7-2 shows the results of running this program.

Example 7.1: IfStatementTest.java

image from book
 1    public class IfStatementTest { 2      public static void main(String[] args){ 3       int int_i = Integer.parseInt(args[0]); 4       int int_j = Integer.parseInt(args[1]); 5 6       if(int_i < int_j) 7       System.out.println(int_i + " is less than " + int_j); 8     } 9   }
image from book

image from book
Figure 7-2: Results of Running Example 7.1

Referring to example 7.1 — the command-line input is converted from Strings to ints and assigned to the variables int_i and int_j on lines 3 and 4. The if statement begins on line 6. The less-than operator < is used to compare the values of int_i and int_j. If the value of int_i is less than the value of int_j then the statement on line 7 is executed. If not, line 7 is skipped and the program exits.

Executing Code Blocks in if Statements

More likely than not you will want to execute multiple statements in the body of an if statement. To do this simply enclose the statements in a set of braces to create a code block. Example 7.2 gives an example of such a code block. Figure 7-3 shows the results of executing this program.

Example 7.2: IfStatementTest.java (mod 1)

image from book
 1    public class IfStatementTest { 2      public static void main(String[] args){ 3       int int_i = Integer.parseInt(args[0]); 4       int int_j = Integer.parseInt(args[1]); 5 6       if(int_i < int_j) { 7          System.out.print("Yes "); 8          System.out.println(int_i + " is less than " + int_j); 9        } 10     } 11   }
image from book

image from book
Figure 7-3: Results of Running Example 7.2

Referring to example 7.2 — notice now that the statements executed by the if statement are contained within a set of braces. The code block begins with the opening brace at the end of line 6 and ends with the closing brace on line 9.

Executing Consecutive if Statements

You can follow one if statement with another if necessary. Example 7.3 gives an example.

Example 7.3: IfStatementTest.java (mod 2)

image from book
 1    public class IfStatementTest { 2      public static void main(String[] args){ 3       int int_i = Integer.parseInt(args[0]); 4       int int_j = Integer.parseInt(args[1]); 5 6       if(int_i < int_j) { 7          System.out.print("Yes "); 8          System.out.println(int_i + " is less than " + int_j); 9       } 10 11      if(int_i >= int_j){ 12         System.out.print("No "); 13         System.out.println(int_i + " is not less than " + int_j); 14      } 15     } 16   }
image from book

image from book
Figure 7-4: Results of Running Example 7.3

When example 7.3 is executed the expressions of both if statements are evaluated. When the program is run with the inputs 5 and 6 the expression of the first if statement on line 6 evaluates to true and its body statements are executed. The second if statement’s expression evaluates to false and its body statements are skipped.

When the program is run a second time using input values 6 and 5 the opposite happens. This time around the first if statement’s expression evaluates to false, its body statements are skipped, and the second if statement’s expression evaluates to true and its body statements are executed.

if/else Statement

When you want to provide two possible execution paths for an if statement add the else keyword to form an if/ else statement. Figure 7-5 provides an execution diagram of the if/else statement.

image from book
Figure 7-5: if/else Statement Execution Diagram

The if/else statement behaves like the if statement, except now, when the expression evaluates to false, the statements contained within the body of the else clause will be executed. Example 7.4 provides the same functionality as example 7.3 using one if/else statement. Figure 7-6 shows the results of running this program.

Example 7.4: IfElseStatementTest.java

image from book
 1    public class IfElseStatementTest { 2      public static void main(String[] args){ 3      int int_i = Integer.parseInt(args[0]); 4      int int_j = Integer.parseInt(args[1]); 5 6      if(int_i < int_j) { 7         System.out.print("Yes "); 8         System.out.println(int_i + " is less than " + int_j); 9       } else { 10         System.out.print("No "); 11         System.out.println(int_i + " is not less than " + int_j); 12         } 13     } 14   }
image from book

image from book
Figure 7-6: Results of Running Example 7.4

Referring to example 7.4 — the if statement begins on line 6. Should the expression evaluate to true the code block that forms the body of the if statement will execute. Should the expression evaluate to false the code block following the else keyword will execute.

Chained if/else Statements

You can chain if/else statements together to form complex programming logic. To chain one if/else statement to another simply follow the else keyword with an if/else statement. Example 7.5 illustrates the use of chained if/else statements in a program.

Example 7.5: ChainedIfElseTest.java

image from book
 1    public class ChainedIfElseTest { 2      public static void main(String[] args){ 3       int int_i = Integer.parseInt(args[0]); 4       int int_j = Integer.parseInt(args[1]); 5 6       if(int_i < int_j) { 7          System.out.print("Yes "); 8          System.out.println(int_i + " is less than " + int_j); 9        } else if(int_i == int_j) { 10                  System.out.print("Exact match! "); 11                  System.out.println(int_i + " is equal to " + int_j); 12               } else{ 13                   System.out.print("No "); 14                   System.out.println(int_i + " is greater than " + int_j); 15                 } 16     } 17   }
image from book

image from book
Figure 7-7: Results of Running Example 7.5

There are a couple of important points to note regarding example 7.5. First, notice how the second if/else statement begins on line 9 immediately following the else keyword of the first if/else statement. Second, notice how indenting is used to aid readability.

switch Statement

The switch statement, also referred to as the switch/case statement, is used in situations where you need to provide multiple execution paths based on the evaluation of a particular int, short, byte, or char value. Figure 7-8 gives the execution diagram for a switch statement.

image from book
Figure 7-8: switch Statement Execution Diagram

When you write a switch statement you will add one or more case clauses to it. When the switch statement is executed, the value supplied in the parentheses of the switch statement is compared with each case value, and a match results in the execution of that case’s code block.

Notice in figure 7-8 how each case’s statements are followed by a break statement. The break statement is used to exit the switch and continue processing.

If a break statement is omitted, execution will fall through to the next case, which may or may not be the behavior you require. Example 7.6 gives an example of the switch statement in action. Figure 7-9 shows the results of running this program.

Example 7.6: SwitchStatementTest.java

image from book
 1    public class SwitchStatementTest { 2      public static void main(String[] args){ 3        int int_i = Integer.parseInt(args[0]); 4 5        switch(int_i){ 6          case 1 : System.out.println("You entered one!"); 7                   break; 8          case 2 : System.out.println("You entered two!"); 9                   break; 10         case 3 : System.out.println("You entered three!"); 11                  break; 12         case 4 : System.out.println("You entered four!"); 13                  break; 14         case 5 : System.out.println("You entered five!"); 15                  break; 16         default: System.out.println("Please enter a value between 1 and 5"); 17       } 18     } 19   }
image from book

image from book
Figure 7-9: Results of Running Example 7.6

Referring to example 7.6 — this program reads a String from the command line and converts it to an integer value using our friend the Integer.parseInt() method. The integer variable int_i is then used in the switch statement. Its value is compared against the five cases. If there’s a match, meaning its value is either 1, 2, 3, 4, or 5, then the related case executes and the appropriate message is printed to the screen. If there’s no match then the default case will execute and prompt the user to enter a valid value.

The switch statement shown in example 7.6 can be rewritten to take advantage of case fall-through. It relies on the help of an array which you will see from studying the code shown in example 7.7.

Example 7.7: SwitchStatementTest.java (mod 1)

image from book
 1    public class SwitchStatementTest { 2      public static void main(String[] args){ 3        int int_i = Integer.parseInt(args[0]); 4        String[] string_array = {"one", "two", "three", "four", "five"}; 5 6        switch(int_i){ 7          case 1 : 8          case 2 : 9          case 3 : 10         case 4 : 11         case 5 : System.out.println("You entered " + string_array[int_i - 1]); 12                  break; 13         default: System.out.println("Please enter a value between 1 and 5"); 14       } 15     } 16   }
image from book

image from book
Figure 7-10: Results of Running Example 7.7

Referring to example 7.7 — although arrays are formally covered in the chapter 8, the use of one in this particular example should not be too confusing to you. A String array, similar to the one used as an argument to the main() method, is declared on line 4. It is initialized to hold five string values: “one”, “two”, “three”, “four”, and “five”. The switch statement is then rewritten in a more streamlined fashion with the help of the string_array. It is used on line 11, with the help of the variable int_i, to provide the text representation of the numbers 1, 2, 3, 4, and 5. The variable int_i is used to index the array but, as you will notice, 1 must be subtracted from int_i to yield the proper array offset.

If you are confused by the use of the array in this example don’t panic. Arrays are covered in painful detail in chapter 8.

Nested Switch Statement

Switch statements can be nested to yield complex programming logic. Study example 7.8.

Example 7.8: NestedSwitchTest.java

image from book
 1 public class NestedSwitchTest { 2  public static void main(String[] args){ 3     char char_c = args[0].charAt(0); 4     int int_i = Integer.parseInt(args[1]); 5 6     switch(char_c){ 7       case 'U' : 8       case 'u' : switch(int_i){ 9                    case 1: 10                    case 2: 11                    case 3: 12                    case 4: 13                    case 5: System.out.println("You entered " + char_c + " and " + int_i); 14                            break; 15                    default: System.out.println("Please enter: 1, 2, 3, 4, or 5"); 16                  } 17                  break; 18       case 'D' : 19       case 'd' : switch(int_i){ 20                    case 1: 21                    case 2: 22                    case 3: 23                    case 4: 24                    case 5: System.out.println("You entered " + char_c + " and " + int_i); 25                            break; 26                    default: System.out.println("Please enter: 1, 2, 3, 4, or 5"); 27                  } 28                  break; 29       default: System.out.println("Please enter: U, u, D, or d"); 30 31     } 32  } 33 }
image from book

image from book
Figure 7-11: Results of Running Example 7.8

Referring to example 7.8 — this program reads two string arguments from the command line. It then takes the first character of the first string and assigns it to the variable char_c. Next, it converts the second string into an int value. The char_c variable is used in the first, or outer, switch statement. As you can see from examining the code it is looking for the characters ‘U’, ‘u’, ‘D’, or ‘d’. The nested switch statements are similar to the one used in the previous example. Notice again that indenting is used to help distinguish between outer and inner switch statements.

Quick Review

Selection statements are used to provide alternative paths of program execution. There are three types of selection statements: if, if/else, and switch. The conditional expression of the if and if/else statements must evaluate to a boolean value of true or false. Any expression that evaluates to boolean true or false can be used. You can chain together if and if/else statements to form complex program logic.

The switch statement evaluates a char, byte, short, or int value and executes a matching case and its associated statements. Use the break keyword to exit a switch statement and prevent case fall through. Always provide a default case.




Java For Artists(c) The Art, Philosophy, and Science of Object-Oriented Programming
Java For Artists: The Art, Philosophy, And Science Of Object-Oriented Programming
ISBN: 1932504052
EAN: 2147483647
Year: 2007
Pages: 452

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