The Switch Statement

Learn about the useful switch statement and how it is an alternative popular statement to use

The form of a Switch Statement

The versatile switch statement is an alternative to the 'if' statement and has many possible executions. Along with some complex data types, the switch statement can be expressed with the int, short, byte or char primitive data types, and since Java 7, it works with the String class.

Here is an example of the basic structure of a switch statement:

switch( variableName ) {        //variableName must correlate to an acceptable data type.

    case value1: 
        statement(s);           //if value corresponds to variableName, statements are expressed.
        break;                  //necessary to end the case block(case and corresponding statements).

    case value2:                //switch statements made up of multiple cases.
        statement(s);
        break;                  //default accounts for a value of varaibleName not covered by a case.

    case ... :
        ... ;
        break;

    default: 
        statements(s);
        break;           
    }

How to use the Switch Statement

We have the keyword switch followed by a variable representing a primitive data type and then open and close curly braces. Contained within the curly braces is the switch block. The switch block is a series of statements broken up with case labels. Each case label is assigned a value which can be represented by a number or a string.

Here we have an example of switch statement code using the int data type.

class SwitchExample {
    public static void main(String[] args){

     int dayOfTheWeek = 4;

     String day;    

        switch( dayOfTheWeek ){
            case 1: 
                day = "Monday";
                break;
            case 2:
                day = "Tuesday";
                break;
            case 3:
                day = "Wednesday";
                break;
            case 4:
                day = "Thursday";
               break;
            case 5:
                day = "Friday";
                break;
            case 6:
                day = "Saturday";
                break;
            case 7:
                day = "Sunday";
                break;
            default: 
                day = "Invalid day";
                break;
        }

        System.out.println(day);

    }

}

This code output is:

Thursday

Individual break statements for each case keep the code from falling through. This is when a case matching the switch expression is found and then, if there is no break statement, every subsequent case and corresponding statements are also executed, until a break is reached.

The default label is commonly, used when the expression in the switch statement does not meet a defined case label. If the expression in the switch parenthesis is not met by a defined case the default label is invoked the and corresponding statement is executed.

Here is an example of a switch statement falling through:

class SwitchExample {

    public static void main(String[] args) {

        int dayOfTheWeek = 4;

        switch( dayOfTheWeek ) {
            case 1: 
                System.out.println("Monday");
                break;

            case 2:
                System.out.println("Tuesday");
                break;

            case 3:
                System.out.println("Wednesday");
                break;

            case 4:
                System.out.println("Thursday");
                                                //Missing break statement.
            case 5:
                System.out.println("Friday");
                                                //Missing break statement.
            case 6:
                System.out.println("Saturday");
                                                //Missing break statement.
            case 7:
                System.out.println("Sunday");
                break;

            default: 
                break;
        }
    }
}

The output for this code is:

    Thursday
    Friday
    Saturday
    Sunday

It is also possible for cases in a switch to share statements, that is to say several case labels can correspond to the same statements. Case labels will share statements in order to avoid code redundancy.

import java.util.scanner

class SwitchExample {

    public static void main(String[] args) {

            int numberOfEyes;

            Scanner input = new Scanner(System.in);

            System.out.println("How many eyes do you have? ");   

            numberOfEyes = input.nextInt();

            switch(numberOfEyes){

                case 1:
                    System.out.println("You are a Cyclops!");
                     break;

                 case 2:
                     System.out.println("You are most likely a vertebrate");
                     break;

                case 3: case 4: case 5:
                case 6: case 7: 
                     System.out.println("You are some weird creature...probably slimy!");
                     break;

                case 8: 
                     System.out.println("Ah, spider, stay back!");
                      break;

                default: 
                     System.out.println("Too many eyes...or not enough!");
                        break;
        }
    }
}

In this example, the cases of creatures with between three and seven eyes share the same statement. The output will be the same for any number that falls within this range.

Using Strings with the Switch Statement

Apart from the primitive data types, switch statements can also evaluate a String. By replacing the number value for each case with a string, we redefine the case label.

import java.util.Scanner;

public class SwitchString {

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);

        String color;

        System.out.println("Enter a color: ");
        color = input.next();

        switch(color.toLowerCase()){
            case "blue":
                System.out.println("The sky is " + color);
                break;

            case "red":
                System.out.println("The traffic light is " + color);
                break;

            case "green":
                System.out.println("The grass is " + color);
                break;

            case "yellow":
                System.out.println("The sun is " + color);
                break;

            default:
                System.out.println("Color not found.  Maybe try a primary color next time.");
                break;
        }

    }
}

If one of the colors entered matches one of our cases then the output will be the statement corresponding to that case, otherwise the default statement will be the output.

Switch statements can be utilized in many ways and it is chiefly employed to avoid excessive repetition of code for if statements. However, sometimes an if statement will be more more efficient for whatever program you are writing as switch statements are often used to test one variable at a time.

Comments

blog comments powered by Disqus