5.2. The switch statement

[3.4] Use a switch statement

In this section, you’ll learn how to use the switch statement and see how it compares to nested if-else constructs. You’ll learn the right ingredients for defining values that are passed to the switch labels and the correct use of the break statement in these labels.

5.2.1. Create and use a switch statement

You can use a switch statement to compare the value of a variable with multiple values. For each of these values, you can define a set of statements to execute.

The following example uses a switch statement to compare the value of the variable marks with the literal values 10, 20, and 30, defined using the case keyword:

A switch statement can define multiple case labels within its switch block but only a single default label. The default label executes when no matching value is found in the case labels. A break statement is used to exit a switch statement, after the code completes its execution for a matching case.

5.2.2. Comparing a switch statement with multiple if-else constructs

A switch statement can improve the readability of your code by replacing a set of (rather complicated-looking) related if-else-if-else statements with a switch and multiple case statements.

Examine the following code, which uses if-else-if-else statements to check the value of a String variable day and display an appropriate message:

Now examine this implementation of the preceding code using the switch statement:

String day = "SUN";
switch (day) {
    case "MON":
    case "TUE":

    case "WED":
    case "THU": System.out.println("Time to work");
                break;
    case "FRI": System.out.println("Nearing weekend");
                break;
    case "SAT":
    case "SUN": System.out.println("Weekend!");
                break;
    default: System.out.println("Invalid day?");
}

The two preceding snippets of code perform the same function of comparing the value of the variable day and printing an appropriate value. But the latter code, which uses the switch statement, is simpler and easier to read and follow.

Note that the preceding switch statement doesn’t define code for all the case values. What happens if the value of the variable day matches TUE? When control of the code enters the label matching TUE in the switch construct, it’ll execute all the code until it encounters a break statement or it reaches the end of the switch statement.

Figure 5.7 depicts the execution of the multiple if-else-if-else statements used in the example code in this section. You can compare it to a series of questions and answers that continue until a match is found or all the conditions are evaluated.

Figure 5.7. The if-else-if-else construct is like a series of questions and answers.

As opposed to an if-else-if-else construct, you can compare a switch statement to asking a single question and evaluating its answer to determine which code to execute. Figure 5.8 illustrates the switch statement and its case labels.

Figure 5.8. A switch statement is like asking a question and acting on the answer.

Exam Tip

The if-else-if-else construct evaluates all the conditions until it finds a match. A switch construct compares the argument passed to it with its labels.

See if you can find the twist in the next exercise. Hint: It defines code to compare String values (answer can be found in the appendix).

Twist in the Tale 5.2

Modify the code used in the previous example as follows. What’s the output of this code?

String day = new String("SUN");
switch (day) {
    case "MON":
    case "TUE":
    case "WED":
    case "THU": System.out.println("Time to work");
                break;
    case "FRI": System.out.println("Nearing weekend");
                break;
    case "SAT":
    case "SUN": System.out.println("Weekend!");
                break;
    default: System.out.println("Invalid day?");
}

  1. Time to work
  2. Nearing weekend
  3. Weekend!
  4. Invalid day?

5.2.3. Arguments passed to a switch statement

You can’t use the switch statement to compare all types of values, such as all types of objects and primitives. There are limitations on the types of arguments that a switch statement can accept.

Figure 5.9 shows the types of arguments that can be passed to a switch statement and to an if construct.

Figure 5.9. Types of arguments that can be passed to a switch statement and an if construct

A switch statement accepts arguments of types char, byte, short, int, and String (starting in Java version 7). It also accepts arguments and expressions of types enum, Character, Byte, Integer, and Short. Because enums aren’t on the OCA Java SE 8 Programmer I exam objectives, I won’t discuss them any further. The switch statement doesn’t accept arguments of type long, float, or double, or any object besides String.

Apart from passing a variable to a switch statement, you can also pass an expression to the switch statement as long as it returns one of the allowed types. The following code is valid:

The following code won’t compile because the type of history is double, which is a type that isn’t accepted by the switch statement:

Exam Tip

Watch out for questions in the exam that try to pass a primitive decimal type such as float or double to a switch statement. Code that tries to do so will not compile.

For nonprimitive types, that is, String and wrapper types, the switch argument must not be null, which would cause a NullPointerException to be thrown:

In the preceding code, if the variable value is assigned the value 10, the code will output value is 10.

Exam Tip

For nonprimitive types, that is, String and wrapper types, the switch argument must not be null, which would cause a NullPointer-Exception to be thrown.

5.2.4. Values passed to the label case of a switch statement

You’re constrained in a couple of ways when it comes to the value that can be passed to the case label in a switch statement, as the following subsections explain.

Case values should be compile-time constants

The value of a case label must be a compile-time constant value; that is, the value should be known at the time of code compilation:

Note that b+c in the preceding code defined at can’t be determined at the time of compilation and isn’t allowed. But 10*7 defined at is a valid case label value.

You can use variables in an expression if they’re marked final because the value of final variables can’t change once they’re initialized:

Because the variables b and c are final variables here, at the value of b+c can be known at compile time. This makes it a compile-time constant value, which can be used in a case label.

You may be surprised to learn that if you don’t assign a value to a final variable with its declaration, it isn’t considered a compile-time constant:

This code defines a final variable c at line but doesn’t initialize it. The final variable c is initialized at line . Because the final variable c isn’t initialized with its declaration, at the expression b+c isn’t considered a compile-time constant, so it can’t be used as a case label.

Case values should be assignable to the argument passed to the switch statement

Examine the following code, in which the type of argument passed to the switch statement is byte and the case label value is of the type float. Such code won’t compile:

Null isn’t allowed as a case label

Code that tries to compare the variable passed to the switch statement with null won’t compile, as demonstrated in the following code:

One code block can be defined for multiple cases

It’s acceptable to define a single code block for multiple case labels in a switch statement, as shown by the following code:

This example code will output Average score if the value of the variable score matches any of the values 100, 50, and 10.

5.2.5. Use of break statements within a switch statement

In the previous examples, note the use of break to exit the switch construct once a matching case is found. In the absence of the break statement, control will fall through the remaining code and execute the code corresponding to all the remaining cases that follow that matching case.

Consider the examples shown in figure 5.10—one with a break statement and the other without a break statement. Examine the flow of code (depicted using arrows) in this figure when the value of the variable score is equal to 50.

Figure 5.10. Differences in code flow for a switch statement with and without break statements

Our (hypothetical) enthusiastic programmers, Harry and Selvan, who are also preparing for this exam, sent in some of their code. Can you choose the correct code for them in the following Twist in the Tale exercise? (The answer is in the appendix.)

Twist in the Tale 5.3

Which of the following code submissions by our two hypothetical programmers, Harry and Selvan, examines the value of the long variable dayCount and prints out the name of any one month that matches the day count?

  1. Submission by Harry:
    long dayCount = 31;
    if (dayCount == 28 || dayCount == 29)
        System.out.println("Feb");
    else if (dayCount == 30)
        System.out.println("Apr");
    else if (dayCount == 31)
        System.out.println("Jan");
  2. Submission by Selvan:
    long dayCount = 31;
    switch (dayCount) {
        case 28:
        case 29: System.out.println("Feb"); break;
        case 30: System.out.println("Apr"); break;
        case 31: System.out.println("Jan"); break;
    }

In the next section, I’ll cover the iteration statements known as loop statements. Just as you’d like to repeat the action of “eating an ice cream” every day, loops are used to execute the same lines of code multiple times. You can use a for loop, an enhanced for (for-each) loop, or the do-while and while loops to repeat a block of code. Let’s start with the for loop.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.103.204