Saturday 9 May 2015

Controlling Your Program in Java - Selection Statement

The Java keywords for controlling program flow are nearly identical to C and C++. This is one of the most obvious ways in which Java shows its legacy as a derivative of these two languages. In this section, you will see how to use Java's control flow commands to write methods.

Selection

The Java language provides two alternative structures-ifstatements and switch statements-for selecting among alternatives. Although it would be possible to spend your entire Java programming career using only one of these at the expense of the other, each has its definite advantages.

The if Statement

A Java if statement is a test of any Boolean expression. If the Boolean expression evaluates to true, the statement following the if is executed. On the other hand, if the Boolean expression evaluates to false, the statement following the ifis not executed. For example, consider the following code fragment:
import java.util.Date;

Date today = new Date();
if (today.getDay == 0) then
    System.out.println("It is Sunday.");
This code uses the java.Util.Datepackage and creates a variable named todaythat will hold the current date. The getDaymember method is then applied to todayand the result compared to 0. A return value of 0 for getDayindicates that the day is Sunday, so if the Boolean expression today.getDay == 0 is true, a message is displayed. If today isn't Sunday, no action occurs.
If you are coming to Java from a C or C++ background, you may have been tempted to rewrite the preceding example as follows:
import java.util.Date;

Date today = new Date();
if (!today.getDay) then
    System.out.println("It is Sunday.");
In C and C++, the expression !today.getDaywould evaluate to 1 whenever today.getDay evaluated to 0 (indicating Sunday). In Java, the expression used within an ifstatement must evaluate to a Boolean. Therefore, this code doesn't work because !today.getDaywill evaluate to 0 or 1, depending on which day of the week it is. And, as you learned earlier in this chapter, integer values cannot be cast to Boolean values. This is, of course, an example where Java's nuances may take a little getting used to for C and C++ programmers. Once you're accustomed to the change, however, you will find your code more readable, reliable, and maintainable.
Of course, an if statement without an else is as incomplete as a Labrador Retriever without a bandanna around his neck. Not wanting to be accused of cruelty to animals or programmers, the Java developers included an elsestatement that can be executed whenever an ifstatement evaluates to false. This can be seen in the following sample code:
import java.util.Date;

Date today = new Date();
if (today.getDay == 0) then
    System.out.println("It is Sunday."); 
else
    System.out.println("It is NOT Sunday.");
In this case, the same message will be displayed whenever it is Sunday, but a different message will be displayed whenever it is not Sunday. Both examples so far have only shown the execution of a single statement within the ifor the else cases. By enclosing the statements within curly braces, you can execute as many lines of code as you'd like. This can be seen in the following example that makes some suggestions about how to spend each day of the week:
import java.util.Date;

Date today = new Date();
if (today.getDay == 0) then {
    System.out.println("It is Sunday."); 
    System.out.println("And a good day for golf.");
}
else {
    System.out.println("It is NOT Sunday."); 
    System.out.println("But still a good day for golf.");
}
Because it's possible to execute whatever code you desire in the else portion of an if…elseblock, you may have already reasoned that it is possible to execute another if statement inside the else statement of the first if statement. This is commonly known as an if…else if…else block, an example of which follows:
import java.util.Date;

Date today = new Date();
if (today.getDay == 0) then
    System.out.println("It is Sunday."); 
else if (today.getDay == 1) then
    System.out.println("It is Monday."); 
else if (today.getDay == 2) then
    System.out.println("It is Tuesday."); 
else if (today.getDay == 3) then
    System.out.println("It is Wednesday."); 
else if (today.getDay == 4) then
    System.out.println("It is Thursday."); 
else if (today.getDay == 5) then
    System.out.println("It is Friday."); 
else
    System.out.println("It must be Saturday.");

The switch Statement

As you can see from the previous code sample, a lengthy series of if…else if…elsestatements can get convoluted and hard to read as the number of cases increases. Fortunately, you can avoid this problem by using Java's switch statement. Like its C and C++ cousins, the Java switchstatement is ideal for testing a single expression against a series of possible values and executing the code associated with the matching case statement, as shown in the following example:
import java.util.Date;

Date today = new Date();
switch (today.getDay) {
    case 0:    // Sunday 
        System.out.println("It is Sunday.");
        break;
    case 1:    // Monday 
        System.out.println("It is Monday.");
        break;
    case 2:    // Tuesday 
        System.out.println("It is Tuesday.");
        break;
    case 3:    // Wednesday 
        System.out.println("It is Wednesday.");
        break;
    case 4:    // Thursday 
        System.out.println("It is Thursday.");
        break;
    case 5:    // Friday 
        System.out.println("It is Friday.");
        System.out.println("Have a nice weekend!");
        break;
    default:   // Saturday 
        System.out.println("It must be Saturday.");
}
System.out.println("All done!");
You should have noticed that each day has its own casewithin the switch. The Saturday case (where today.getDay= 6) is not explicitly given but is instead handled by the defaultcase. Any switch block may include an optional defaultcase that will handle any values not caught by an explicit case.
Within each case, there can be multiple lines of code. The block of code that will execute for the Friday case, for example, contains three lines. The first two lines will simply display informational messages, but the third is a breakstatement. The keyword breakis used within a case statement to indicate that the flow of the program should move to the first line following the switchblock. In this example, breakappears as the last statement in each case except the default and will cause program execution to move to the line that prints "All done!" The breakstatement was left out of the default block because by that point in the code, the switch block was ending, and there was no point in using an explicit command to exit the switch.
If, as the previous example seems to imply, you always need to include a break statement at the end of each block, why not just leave breakout and have Java assume that after a block executes, control should move outside the switchblock? The answer is that there are times when you do not want to break out of the switchstatement after executing the code for a specific case value. For example, consider the following code that could be used as a scheduling system for physicians:
import java.util.Date;

Date today = new Date();
switch (today.getDay) {
    case 0:      // Sunday
    case 3:      // Wednesday
    case 6:      // Saturday
        System.out.println("It's Golf Day!");
        break;
    case 2:      // Tuesday
        System.out.println("Tennis at 8:00 am");
    case 1:      // Monday
    case 4:      // Thursday
    case 5:      // Friday
        System.out.println("Office Hours: 10:00 - 5:00");
        break;
}
System.out.println("All done!");
This example illustrates a couple of key concepts about switchstatements. First, you'll notice that it is possible to have multiple cases execute the same block of code, as follows:
case 0:      // Sunday

case 3:      // Wednesday
case 6:      // Saturday
    System.out.println("It's Golf Day!"); 
    break;
This code will result in the message "It's Golf Day" being displayed if the current day is Wednesday, Saturday, or Sunday. If you collect the three cases together without any intervening break statements, each will execute the same code. But consider what happens on Tuesday when the following code executes:
case 2:      // Tuesday

    System.out.println("Tennis at 8:00 am");
Certainly a reminder about the message match will be displayed, but this case doesn't end with a breakstatement. Because Tuesday's code doesn't end with a breakstatement, the program will continue executing the code in the following cases until a breakis encountered. This means that Tuesday's code flows into the code used for Monday, Thursday, and Friday as shown in the following:
case 2:      // Tuesday

    System.out.println("Tennis at 8:00 am");
case 1:      // Monday
case 4:      // Thursday
case 5:      // Friday
    System.out.println("Office Hours: 10:00 - 5:00");
    break;
This will result in the following messages being displayed every Tuesday:
Tennis at 8:00 am

Office Hours: 10:00 - 5:00
On Monday, Thursday, and Friday, only the latter message will display.
In addition to writing switchstatements that use integer cases, you can use character values as shown in the following example:

switch (aChar) {

    case 'a':
    case 'e':
    case 'i':
    case 'o':
    case 'u':
        System.out.println("It's a vowel!");
        break;
    default:
        System.out.println("It's a consonant!");
}

No comments:

Post a Comment