Conditional Statements


Java™ 2 Primer Plus
By Steven Haines, Steve Potts

Table of Contents
Chapter 4.  Flow Control

Consider drawing a graph in a Java application that displays the pressure level of a nuclear plant with requirements that normal values are green, warning values are yellow, and dangerous values are red. Assign the following values to these conditions:

  • Pressure levels of 0% to 70% are displayed as normal

  • Pressure levels of 71% to 90% are displayed as a warning

  • Pressure levels greater than 90% are displayed as dangerous

Conditional statements enable you to look at the value of a variable, and then decide on the statements of code that you would like to execute. Java provides support for conditional statements through the following two mechanisms: if-then-else statements and switch statements

The if-then-else Statements

If statements are the most simple and straightforward mechanism for implementing a conditional statement. In its simplest form you ask the question of whether some conditional value is true, and if so, you execute a set of code. The general form of an if statement is

 if( boolean_value ) {      // Execute these statements  } 

The if statement accepts a Boolean value, or an expression that evaluates to a Boolean value, and executes the code enclosed in the following braces if that value is true. If that value is false, the program continues executing the program at the first statement following the if statement's closing brace. Consider the following example:

 System.out.println( "I will examine your age" );  if( age < 18 ) {     System.out.println( "You are a child   kids rule!" );  }  System.out.println( "Let's continue" ); 

If age is defined to be 10, you will see the following output:

 I will examine your age  You are a kid   kids rule!  Let's continue 

If age is defined to be 20, you will only see the following output:

 I will examine your age  Let's continue 

That served well for executing a set of code only if a specific condition was true, but how could you execute code if a condition was true, and then execute different code if the condition was false? Looking at the structure of the if statement, you could do the following:

 if( age < 18 ) {     System.out.println( "You are a child   kids rule!" );  }  if( age >= 18 ) {     System.out.println( "You are an adult   adults are alright!" );  } 

Writing two if statements, each checking for different values is perfectly legal and effective, but it is not very efficient. From the first if statement, the program knows what age is and whether it is less than or greater than 18, so how can the compiler make use of this information? The answer is through another keyword: else. else accepts no parameters and follows an if statement block. For example:

 if( age < 18 ) {     System.out.println( "You are a child   kids rule!" );  }  else {     System.out.println( "You are an adult   adults are alright!" );  } 

The else statement that follows the if statement block says that if the condition in the preceding if evaluates to false, execute the else statement block.

Now consider that you would like to differentiate between children, adults, and seniors. The if statement's else clause offers the ability to perform additional comparisons. The complete form of the if statement is as follows:

 if( condition ) {     // statements;  }  else if( another_condition ) {     // statements;  }  else if( some other condition ) {     // statements;  }  else {     // statements;  } 

Between the if and else clauses can appear any number of else if clauses. These else if clauses, like the if clause, accepts conditions that if evaluated to true cause that block of code to be execute. Furthermore, when a true condition is met, the rest of the conditions are not evaluated and the if statement is completed.

 if( age < 18 ) {     System.out.println( "You are a child   kids rule!" );  }  else if( age < 55 ) {     System.out.println( "You are an adult   adults are alright!" );  }  else {     System.out.println( "You are a senior   seniors are great!" );  } 

Before leaving this section, here is the solution to the aforementioned nuclear plant example using if statements:

 if( pressure < 70 ) {     System.out.println( "Normal   green" );  }  else if( pressure < 90 ) {     System.out.println( "Warning   yellow" );  }  else {     System.out.println( "Danger   red   hit the ground!" );  } 

Blocks of Statements


You might have noticed that each of the aforementioned if statements had blocks of statements that were executed based on the result of the condition. Although the braces that denote a block of statements is readable and offers support for multiple lines of Java code to be executed, the braces are not necessary. This is only true if a single statement is to be executed. In this case the braces can be omitted, as follows:

 if( condition )     // true statement;  else     // false statement; 

Understand that if you have multiple statements to execute then this shortcut will not work. Consider the following:

 if( condition )     // true statement 1;     // true statement 2;  else     // false statement 1;     // false statement 2; 

When there are no braces, the compiler executes a single statement, and then it considers the if statement complete. Here is how the compiler would add braces to this example:

 if( condition ) {     // true statement 1;  }  // true statement 2;  else  // compiler error!  // false statement 1;  // false statement 2; 

Note that the else statement generates a compiler error because it is not considered part of the previous if statement. Thus, you would have to do the following:

 if( condition ) {     // true statement 1;     // true statement 2;  }  else {     // false statement 1;     // false statement 2;  } 

Ternary Operator

You might have already made the association between the ternary operator and the if-then-else statement, and you are right, it has very similar behavior to a simple if-else block. To review, the form of the ternary operator is

 condition ? true statement : false statement; 

The condition is evaluated and if it is true, the true statement is executed; or if it is false, the false statement is executed. This could be expressed using the if statement as follows:

 if( condition ) {     // true statement(s);  }  else {     // false statement(s);  } 

The ternary operator presents this same functionality, but its intention is based on returning or computing a value to be returned to the caller based on a condition. For example:

 boolean letIntoClub = ( age >= 18 ) ? true : false; 

The ternary operator is functionally similar to a simple if statement, but each has a distinct purpose.

The switch Statement

The if statement is very useful, but what happens when you have several values that you want to work with? Consider defining the column names for a table: id, name, address, and phone number. Assign values to these columns starting with 0 and counting up to 3. Using an if statement, this would be accomplished as follows:

 if( col == 0 ) {    System.out.println( "id" );  }  else if( col == 1 ) {    System.out.println( "name" );  }  else if( col == 2 ) {    System.out.println( "address" );  }  else if( col == 3 ) {    System.out.println( "phone number" );  }  else {     System.out.println( "unknown" );  } 

In Java programming performing certain actions based on specific numeric values is quite common, so common in fact that there is another construct in the language defined to handle it. The switch statement enables you to make a choice between multiple alternative execution paths based on an integer value (or any value that can be converted to an integer). The general form of the switch statement is

 switch( variable ) {  case value_1:     // statements     break;  case value_2:     // statements     break;  ...  default:     // default statements  } 

The variable must be an int or be able to be converted to an int. The new keywords in the switch statement are

  • switch: Denotes the start of the switch statement and uses the variable passed to it through its parentheses for all comparisons

  • case: Notes the comparison of the variable to the specified value

  • break (optional): Causes execution to continue at the statement immediately following the switch block

Consider the aforementioned table column example and convert it to use a switch statement:

 switch( col ) {  case 0:     System.out.println( "id" );     break;  case 1:     System.out.println( "name" );     break;  case 2:     System.out.println( "address" );     break;  case 3:     System.out.println( "phone" );     break;  default:     System.out.println( "unknown" );  } 

The switch statement converts col to an int, if it is not one already, and then compares its value to the values specified in each of the four case statements. If the value of col is 0 it prints id, if it is 1 it prints name, and so on. If the value of col does not match any of the cases, it executes the statements following the default statement.

The next question you must have concerns the break statement. The break statement causes execution to continue at the statement immediately following the switch block, but what happens if the break statement is omitted? The answer is that the execution continues with the next statement, which might be a statement for another case value. Consider omitting the break statements in the previous example:

 switch( col ) {  case 0:     System.out.println( "id" );  case 1:     System.out.println( "name" );  case 2:     System.out.println( "address" );  case 3:     System.out.println( "phone" );  default:     System.out.println( "unknown" );  } 

Consider the output for col with a value of 1. The first statement executed would be to print name, the next statement is not a break, so it continues and prints address, phone, and finally unknown:

 Output:  name  address  phone  unknown 

This effect is referred to as falling through, and can be useful if there are several values that should perform the same function. Consider the following example:

 switch( number ) {  case 2:  case 4:  case 6:  case 8:  case 10:     System.out.println( "Even" );     break;  case 1:  case 3:  case 5:  case 7:  case 9:     System.out.println( "Odd" );     break;  default:     System.out.println( "Number is not between 1 and 10" ); 

If number is an even number between 1 and 10 the switch statement prints "Even", if number is an odd number between 1 and 10 the switch statement prints "Odd", else it prints "Number is not between 1 and 10". In this case the fall through effect was very beneficial! You can still add statements in the body of one case statement, and let it fall through to the results.


    Java 2 Primer Plus
    Java 2 Primer Plus
    ISBN: 0672324156
    EAN: 2147483647
    Year: 2001
    Pages: 332

    Similar book on Amazon © 2008-2017.
    If you may any questions please contact us: