Chapter 9

The if and switch Statements


CONTENTS

In previous chapters, you've learned a lot about the way Java works. You now know how to type and compile programs, how to input and output simple data, how to perform mathematical operations, and how to perform comparisons using logical expressions. But these techniques are merely the building blocks of a program. To use these building blocks in a useful way, you have to understand how computers make decisions.

In this chapter, you learn how your programs can analyze data in order to decide what parts of your program to execute. Until now, your applets have executed their statements in strict sequential order, starting with the first line of a method and working, line by line, to the end of the method. Now it's time to learn how you can control your program flow-the order in which the statements are executed-so that you can do different things based on the data your program receives.

Controlling Program Flow

Program flow is the order in which a program executes its statements. Most program flow is sequential, meaning that the statements are executed one by one in the order in which they appear in the program or method. However, there are Java commands that make your program jump forward or backward, skipping over program code not currently required. These commands are said to control the program flow.

If the idea of computers making decisions based on data seems a little strange, think about how you make decisions. For example, suppose you're expecting an important letter. You go out to your mailbox and look inside. Based on what you find, you choose one of two actions:

In either case, you've made a decision based on whether there is mail in the mailbox. This is called conditional branching.

Computers use this same method to make decisions (except they never complain and they don't give a darn how late your mail is). You will see the word if used frequently in computer programs. Just as you might say to yourself, "If the mail is in the mailbox, I'll bring it in," a computer also uses an if statement to decide what action to take.

Program Flow and Branching

Most programs reach a point where a decision must be made about a piece of data. The program must then analyze the data, decide what to do about it, and jump to the appropriate section of code. This decision-making process is as important to computer programming as pollen is to a bee. Virtually no useful programs can be written without it.

When a program breaks the sequential flow and jumps to a new section of code, it is called branching. When this branching is based on a decision, the program is performing conditional branching. When no decision-making is involved and the program always branches when it encounters a branching instruction, the program is performing unconditional branching. Unconditional branching is rarely used in modern programs, so this chapter deals with conditional branching.

The if statement

Most conditional branching occurs when the program executes an if statement, which compares data and decides what to do next based on the result of the comparison. For example, you've probably seen programs that print menus on-screen. To select a menu item, you often type the item's selection number. When the program receives your input, it checks the number you entered and decides what to do. You'd probably use an if statement in this type of program.

A simple if statement includes the keyword if followed by a logical expression, which, as you learned in the previous chapter, is an expression that evaluates to either true or false. These expressions are surrounded by parentheses. You follow the parentheses with the statement that you want executed if the logical expression is true. For example, look at this if statement:


if (choice == 5)

    g.drawString("You chose number 5.", 30, 30);

In this case, if the variable choice is equal to 5, Java will execute the call to drawString(). Otherwise, Java will just skip the call to drawString().

Example: The Form of an if Statement

The syntax of languages such as Java are tolerant of the styles of various programmers, enabling programmers to construct programs that are organized in a way that's best suited to the programmer and the particular problem. For example, the Java language is not particular about how you specify the part of an if statement to be executed. For example, the statement


if (choice == 1)

    num = 10;

could also be written like this:


if (choice == 1) num = 10;

In other words, although the parentheses are required around the logical expression, the code to be executed can be on the same line or the line after the if statement.

In the case of an if statement that contains only one program line to be executed, you can choose to include or do away with the curly braces that usually mark a block of code. With this option in mind, you could rewrite the preceding if statement like Listing 9.1.


Listing 9.1  LST9_1.TXT: The if Statement with Braces.

if (choice == 1)

{

    num = 10;

}


Another way you'll often see braces used with an if statement is shown here:


if (choice == 1) {

    num = 10;

}

In this case, the opening brace is on the if statement's first line.

NOTE
Logical expressions are also called Boolean expressions. That is, a Boolean expression is also an expression that evaluates to either true or false. Now you understand why Java has a boolean data type, which can hold the value true or false. Having the boolean data type enables you to assign the result of a logical expression to a variable.

Multiple if Statements

You can use a number of if statements to choose between several conditions. For example, look at the group of if statements in Listing 9.2.


Listing 9.2  LST9_2.TXT: A Group of if Statements.

if (choice == 1)

    num = 1;

if (choice == 2)

    num = 2;

if (choice == 3)

    num = 3;


How do these if statements work? Let's say that when Java executes the program code in Listing 9.2, the variable choice equals 1. When the program gets to the first if statement, it checks the value of choice. If choice equals 1 (which it does, in this case), the program sets the variable num to 1 and then drops down to the next if statement. This time, the program compares the value of choice with the number 2. Because choice doesn't equal 2, the program ignores the following part of the statement and drops down to the next if statement. The variable choice doesn't equal 3 either, so the code portion of the third if statement is also ignored.

Suppose choice equals 2 when Java executes the code in Listing 9.2. When the program gets to the first if statement, it discovers that choice is not equal to 1, so it ignores the num = 1 statement and drops down to the next program line, which is the second if statement. Again, the program checks the value of choice. Because choice equals 2, the program can execute the second portion of the statement; that is, num gets set to 2. Program execution drops down to the third if statement, which does nothing because choice doesn't equal 3.

NOTE
The if statement, no matter how complex it becomes, always evaluates to either true or false. If the statement evaluates to true, the second portion of the statement is executed. If the statement evaluates to false, the second portion of the statement is not executed.

Multiple-Line if Statements

Listings 9.1 and 9.2 demonstrate the simplest if statement. This simple statement usually fits your program's decision-making needs just fine. Sometimes, however, you want to perform more than one command as part of an if statement. To perform more than one command, enclose the commands within curly braces. Listing 9.3 is a revised version of Listing 9.2 that uses this technique.


Listing 9.3  LST9_3.LST: Multiple-Line if Statements.

if (choice == 1)

{

    num = 1;

    num2 = 10;

}



if (choice == 2)

{

    num = 2;

    num2 = 20;

}



if (choice == 3)

{

    num = 3;

    num2 = 30;

}


TIP
Notice that some program lines in Listing 9.3 are indented. By indenting the lines that go with each if block, you can more easily see the structure of your program. Listing 9.3 also uses blank lines to separate blocks of code that go together. The compiler doesn't care about the indenting or the blank lines, but these features make your programs easier for you (or another programmer) to read.

What's happening in Listing 9.3? Suppose choice equals 2. When Java gets to the first if statement, it compares the value of choice with the number 1. Because these values don't match (or, as programmers say, the statement doesn't evaluate to true), Java skips over every line until it finds the next if statement.

This brings Java to the second if statement. When Java evaluates the expression, it finds that choice equals 2, and it executes the second portion of the if statement. This time the second portion of the statement is not just one command, but two. The program sets the values of both num and num2.

This brings the program to the last if statement, which Java skips over because choice doesn't equal 3. Notice that, when you want to set up an if statement that executes multiple lines of code, you must use the curly braces-{ and }-to denote the block of instructions that should be executed.

The else Clause

You might think it's a waste of time for Listing 9.3 to evaluate other if statements after it finds a match for the value of choice. You'd be right, too. When you write programs, you should always look for ways to make them run faster; one way to make a program run faster is to avoid all unnecessary processing. But how, you may ask, do you avoid unnecessary processing when you have to compare a variable with more than one value?

One way to keep processing to a minimum is to use Java's else clause. The else keyword enables you to use a single if statement to choose between two outcomes. When the if statement evaluates to true, the second part of the statement is executed. When the if statement evaluates to false, the else portion is executed. (When the if statement evaluates to neither true nor false, it's time to get a new computer!) Listing 9.4 demonstrates how else works.


Listing 9.4  LST9_4.LST: Using the else Clause.

if (choice == 1)

{

    num = 1;

    num2 = 10;

}

else

{

    num = 2;

    num2 = 20;

}


In Listing 9.4, if choice equals 1, Java sets num to 1 and num2 to 10. If choice is any other value, Java executes the else portion, setting num to 2 and num2 to 20. As you can see, the else clause provides a default outcome for an if statement. A default outcome doesn't help much, however, if an if statement has to deal with more than two possible outcomes (as in the original Listing 9.3). Suppose you want to rewrite Listing 9.3 so that it works the same but doesn't force Java to evaluate all three if statements unless it really has to. No problem. Listing 9.5 shows you how to use the else if clause:


Listing 9.5  LST9_5.LST: Using if and else Efficiently.

if (choice == 1)

{

    num = 1;

    num2 = 10;

}

else if (choice == 2)

{

    num = 2;

    num2 = 20;

}

else if (choice == 3)

{

    num = 3;

    num2 = 30;

}


When Java executes the program code in Listing 9.5, if choice is 1, Java will look at only the first if section and skip over both of the else if clauses. That is, Java will set num to 1 and num2 to 10 and then continue on its way to whatever part of the program followed the final else if clause. Note that, if choice doesn't equal 1, 2, or 3, Java must evaluate all three clauses in the listing but will not do anything with num or num2.

Example: Using the if Statement in a Program

Now that you've studied what an if statement looks like and how it works, you probably want to see it at work in a real program. Listing 9.6 is a Java program that uses the menu example you studied earlier in this chapter, whereas Listing 9.7 is the HTML document that runs the applet. Figure 9.1 shows the applet running in the Appletviewer application.

Figure 9.1 : The Applet6 applet enables you to choose colors.


Listing 9.6  Applet6.java: Using an if Statement in a Program.

import java.awt.*;

import java.applet.*;



public class Applet6 extends Applet

{

    TextField textField1;



    public void init()

    {

        textField1 = new TextField(5);

        add(textField1);

g.drawString("3. Green", 40, 115);

        String s = textField1.getText();

        int choice = Integer.parseInt(s);



        if (choice == 1)

            g.setColor(Color.red);

        else if (choice == 2)

            g.setColor(Color.blue);

        else if (choice == 3)

            g.setColor(Color.green);

        else

            g.setColor(Color.black);



        if ((choice >= 1) && (choice <= 3))

            g.drawString("This is the color you chose.", 60, 140);

        else

            g.drawString("Invalid menu selection.", 60, 140);

    }



    public boolean action(Event event, Object arg)

    {

        repaint();

        return true;

    }

}


Tell Java that the program uses classes in the awt package.
Tell Java that the program uses classes in the applet package.
Derive the Applet6 class from Java's Applet class.
Declare a TextField object called textField1.
Override the Applet class's init() method.
Create the TextField object.
Add the TextField object to the applet.
Initialize the text in the TextField object to "1".
Override the Applet class's paint() method.
Display user instructions in the applet's display area.
Display the color menu on three lines.
Get the text from the TextField object.
Convert the text to an integer.
Select a color based on the value the user entered.
Display a message in the appropriate color.
Override the Applet class's action() method.
Tell Java to redraw the applet's display area.
Tell Java that the action() method finished successfully.

Listing 9.7  APPLET6.htmL: The HTML Document That Runs Applet6.

<title>Applet Test Page</title>

<h1>Applet Test Page</h1>

<applet

    code="Applet6.class"

    width=250

    height=150

    name="Applet6">

</applet>


If you were awake at all during Chapter 7 you should already know how most of the Applet6 applet works. But, there's some new stuff in the paint() method that warrants a close look. First, after converting the user's typed selection from text to an integer, the program uses the integer in an if statement to match up each menu selection with the appropriate color. The setColor() method is part of the Graphics object; you call it to set the color of graphical elements, such as text, that the program draws in the applet's display area. The setColor() method's single argument is the color to set. As you can see, Java has a Color object that you can use to select colors. You'll learn more about the Color object in Chapter 36, "The Java Class Libraries." Notice that, if the user's selection does not match a menu selection, the color is set to black.

After the program sets the color, a second if statement determines which text to display, based on whether the user entered a valid selection. If the user's selection is valid, the program displays "This is the color you chose." in the selected color. Otherwise, the program displays "Invalid menu selection" in black.

The switch Statement

Another way you can add decision-making code to your programs is with the switch statement. The switch statement gets its name from the fact that it enables a computer program to switch between different outcomes based on a given value. The truth is, a switch statement does much the same job as an if statement, but it is more appropriate for situations where you have many choices, rather than only a few. Look at the if statement in Listing 9.8:


Listing 9.8  LST9_8.TXT: A Typical if Statement.

if (x == 1)

    y = 1;

if (x == 2)

    y = 2;

if (x == 3)

    y = 3;

else

    y = 0;


You could easily rewrite the preceding if statement as a switch statement, as shown in Listing 9.9:


Listing 9.9  LST9_9.TXT: Changing an if to a switch.

switch(x)

{

    case 1:

        y = 1;

        break;

    case 2:

        y = 2;

        break;

    case 3:

        y = 3;

        break;

    default:

        y = 0;

}


The first line of a switch statement is the keyword switch followed by the variable whose value will determine the outcome. This variable is called the control variable. Inside the main switch statement (which begins and ends with curly braces) are a number of case clauses, one for each possible value of the switch control variable (the x, in this case). In the above example, if x equals 1, Java jumps to the case 1 and sets y equal to 1. Then, the break statement tells Java that it should skip over the rest of the switch statement.

If x is 2, the same sort of program flow occurs, except Java jumps to the case 2, sets y equal to 2, and then breaks out of the switch. If the switch control variable is not equal to any of the values specified by the various case clauses, Java jumps to the default clause. The default clause, however, is optional. You can leave it out if you want, in which case Java will do nothing if there's no matching case for the control variable.

Example: Using the break Statement Correctly

One tricky thing about switch statements is the various ways that you can use the break statement to control program flow. Look at Listing 9.10:


Listing 9.10  LST9_10.TXT: Using break to Control Program Flow.

switch(x)

{

    case 1:

        y = 1;

    case 2:

        y = 2;

        break;

    case 3:

        y = 3;

        break;

    default:

        y = 0;

}


In this example, funny things happen, depending on whether the control variable x equals 1 or 2. In the former case, Java first jumps to case 1 and sets y equal to 1. Then, because there is no break before the case 2 clause, Java continues executing statements, dropping through the case 2 and setting y equal to 2. Ouch! The moral of the story is: Make sure you have break statements in the right places.

If the outcome of Listing 9.10 was really what you wanted to happen, you'd probably rewrite the switch statement is to look like Listing 9.11:


Listing 9.11  LST9_11.TXT: Rewriting Listing 9.10.

switch(x)

{

    case 1:

    case 2:

        y = 2;

        break;

    case 3:

        y = 3;

        break;

    default:

        y = 0;

}


Here, just as in Listing 9.10, y will end up equal to 2 if x equals 1 or 2. You'll run into this type of switch statement a lot in Java programs. If you're a C or C++ programmer, you've already seen a lot of this sort of thing, so you should feel right at home.

Example: Using the switch Statement in a Program

You've seen that a switch statement is similar in many ways to an if statement. In fact, if and switch statements can easily be converted from one to the other. Listing 9.12 is a new version of Applet6 (called Applet7) that incorporates the menu example by using a switch statement instead of an if statement.


Listing 9.12  APPLET7.JAVA: Using a switch Statement in a Program.

import java.awt.*;

import java.applet.*;



public class Applet7 extends Applet

{

    TextField textField1;



    public void init()

    {

        textField1 = new TextField(5);

        add(textField1);

        textField1.setText("1");

    }



    public void paint(Graphics g)

    {

        g.drawString("Type a menu choice in the above box.", 20, 50);

        g.drawString("1. Red", 40, 75);

        g.drawString("2. Blue", 40, 95);

        g.drawString("3. Green", 40, 115);

        String s = textField1.getText();

        int choice = Integer.parseInt(s);



        switch(choice)

        {

            case 1:

                g.setColor(Color.red);

                break;

            case 2:

                g.setColor(Color.blue);

                break;

            case 3:

                g.setColor(Color.green);

                break;

            default:

                g.setColor(Color.black);

        }



        

if ((choice >= 1) && (choice <= 3))

            g.drawString("This is the color you chose.", 60, 140);

        else

            g.drawString("Invalid menu selection.", 60, 140);

    }



    public boolean action(Event event, Object arg)

    {

        repaint();

        return true;

    }

}


When you run this program, you'll see the same display as the one you saw with Applet6. In fact, from the user's point of view, the program works exactly the same as the previous version. The differences are completely internal.

Summary

Making decisions based on the state of data is an important part of a computer program, and now that you have this chapter behind you, you've made a giant leap forward in your Java programming career. You now have enough Java programming savvy to write simple, yet useful, applets. Of course, that's not to say that there isn't a lot left to learn. But by now you should have a good idea of what a Java applet looks like and how it works. The remainder of this book will fill out the details that make Java applets so powerful.

Review Questions

  1. What is program flow?
  2. Define conditional and unconditional branching.
  3. What are two ways to control program flow?
  4. In the following Java example, if num equals 5, will the second line execute?
    if (choice == 3)
    num2 = choice;
  5. Are there times when you don't need braces with an if statement? Explain.
  6. What's the difference between a logical expression and a Boolean expression?
  7. In Listing 9.13, what happens when choice equals 5?
  8. Compare and contrast the if and switch statements.
  9. What value is assigned to num in Listing 9.14 when choice equals 2?

Listing 9.13  LST9_13.LST: Listing for Question 7.

if (choice == 1)

{

    num = 1;

    num2 = 10;

}

else if (choice == 2)

{

    num = 2;

    num2 = 20;

}



Listing 9.14  LST9_14.TXT: Listing for Question 10.

switch(choice)

{

    case 1:

        num = 1;

        break;

    case 2:

        num = 2;

    case 3:

        num = 3;

        break;

    default:

        num = 0;

}


Review Exercises

  1. Write an if statement that sets the variable num to 1 when choice equals 10.
  2. Write an if statement that sets the variable num to the same value as the control variable choice when choice equals 5, but sets num to 0 in every other case.
  3. Write an if statement that sets the variable num to twice the value of the control variable choice. Valid values for choice are 3, 4, 5, and 6.
  4. Convert the if statement in exercise 3 to a switch statement.
  5. Modify Applet7 so that it displays the text string "One," "Two," "Three," or "Four" when the user enters 1, 2, 3, or 4, respectively. Have the program display "Invalid value" for any other user entry. Figure 9.2 shows what the final applet, called SwitchApplet, should look like. (You can find the solution to this programming problem in the CHAP09 folder of this book's CD-ROM.)
    Figure 9.2 : The SwitchApplet applet converts numbers to words.