Java Switch Statements – Uses, Advantages and Restrictions

In this tutorial, we will discuss what are Java switch statements, how to use them, the allowed data types that can be used in the switch statements and the advantages and restrictions that apply to them.

 

What is a “switch” statement

 

A “switch” statement in Java  is a conditional operator used to direct the execution of an algorithm to a specific code path.  Inside a switch statement, multiple execution paths are defined. The path that is taken will depend upon an input value provided to the switch statement.

 

An analogy can be drawn from the good old days with a telephone switch board. A person calls the switch board staff and asks to be routed to a specific number, and the operator on the switch board will connect your call to a specific routing port, depending on the number you as for.

 

How to use a switch statement

 

The following is an example of a switch statement. The switch statement is fed the character value “grade”, and one of the paths will be executed depending on the value of grade.

 

package com.nullbeans;

public class Main {

    public static void main(String[] args) {


        char grade = 'B';

        switch (grade){
            case 'Á': System.out.println("Excellent!"); break;
            case 'B': System.out.println("Very good!"); break;
            case 'C': System.out.println("Average!"); break;
            case 'D': System.out.println("Poor!"); break;
            case 'E': System.out.println("Very poor!"); break;
            case 'F': System.out.println("Failed"); break;
        }
        
    }
}

 

When running this program, we will get the following output.

 

Very good!

Process finished with exit code 0

 

Let us go over some keywords in that example:

 

switch: This signifies the start of a switch statement. The switch statement takes a single input value to be evaluated.

case: The “case” keyword” signifies an entry point for execution. Each case is defined for a specific value. The entry point can be entered if the input value to the switch statement matches the one in the case. As you can see in our example, since we used the value “B”, we started the execution from the “case B” part of the switch statement.

break: The “break” keyword signals the program to exit the switch statement. It is not mandatory to have the break keyword in each case. However, if it is missing, the program will not exit the switch statement and will continue executing until either a break statement is found, or we exit the program. Let us discuss this in more details in the next section.

 

How does the “break” keyword work

 

The break keyword is a java keyword that allows the execution to exit from its current conditional scope. For example, if it is inside a “while” loop, the program will skip the execution of the loop and will exit the loop’s scope. Similarly, if the break keyword is encountered inside a switch statement, it will prompt Java to exit the while switch statement.

 

Take for example the following diagram. Since the code of every case is followed by a “break”, only that code will be executed.

 

This diagram illustrates a switch statement with a break after each case. Since there is a break after each case, only the code related to the single matching case is executed. (Click to enlarge)

 

In our previous program, only one statement was executed, since after each case, a break keyword was present. So what if we did not have a break keyword? Then the program will continue execution until either a break statement is encountered or the end of the switch statement is reached.

 

This diagram illustrates a switch statement where case 1 and case 3 do not have the break keywords. Using this setup, if X is equal to 1, then the code from case 1 and 2 is executed. The program stops at case 2 because there is a break keyword there. If X is equal to 2, then only the code from case 2 is executed. If X is equal to 3, then the code from case 3 is executed and the switch statement is terminated. (Click to enlarge)

 

Let us discuss the next example. The following program is used to print out the features a customer would get when they choose a hosting plan from our imaginary web hosting provider. We can describe the plans as follows:

 

  • Our plans start with a “Basic” package with 2 free domain names.
  • Then there is a “Basic plus” plan, which includes whatever is in the “Basic” plan plus unlimited bandwidth.
  • Then comes the “Premium” plan which includes whatever is in “Basic plus” and “Basic”, plus an extra 1GB of RAM.
  • And finally, there comes the “Premium plus” plan. The plan includes whatever is in the “Premium”, the “Basic plus” and the “Basic”, plus an extra 1 CPU.

 

Now, let us model this program in Java using a switch statement. Since we can ristrict the entry point using the “case” keyword, we can write our program in a way that includes all the correct features by simply defining the switch case order from the most inclusive case to the least inclusive.

 

        String hostingPlan = "Premium";

        System.out.println("Your hosting plan includes:");

        switch(hostingPlan){

            case "Premium plus": System.out.println("- Extra 1 CPU");
            case "Premium": System.out.println("- Extra 1GB RAM");
            case "Basic plus": System.out.println("- Unlimited bandwidth");
            case "Basic": System.out.println("- 2 Domain names");
        }

 

Let us run our program and check the results.

 

Your hosting plan includes:
- Extra 1GB RAM
- Unlimited bandwidth
- 2 Domain names

Process finished with exit code 0

 

Notice here that the println statement of the “Premium plus” case was not executed as the program did not enter the switch statement in this case. The program entered from the “Premium” case. Notice also that, even though the input value “Premium” did not match the “Basic plus” and “Basic” cases, the statements from these cases were executed anyway. This is because the break statement was missing. Therefore, nothing stopped the execution of the rest of the switch statement cases.

 

The “default” case

 

What if the input to the switch statement did not match any of the cases? Then non of the statements would be executed. What if we wanted to print out an error, to tell the user that they inserted an unrecognized value? The default case comes to the rescue.

 

The default case is a a switch statement case which is executed if non of the other switch cases matches the switch statement input. Let us modify our previous example to include a default case.

 

        String hostingPlan = "Super premium";

        System.out.println("Your hosting plan includes:");

        switch(hostingPlan){

            case "Premium plus": System.out.println("- Extra 1 CPU");
            case "Premium": System.out.println("- Extra 1GB RAM");
            case "Basic plus": System.out.println("- Unlimited bandwidth");
            case "Basic": System.out.println("- 2 Domain names"); break;
            default: System.out.println("Hosting plan not recognized");

        }

 

Notice that we added the “break” keyword after the “Basic” case in order to stop the execution of the switch statement if one of the cases match. Now let us run the program.

 

Your hosting plan includes:
Hosting plan not recognized

Process finished with exit code 0

 

Since non of the switch cases matches the input “Super premium”, the default case was executed, Please note that the default case does not need to be the last case in the switch statement. It can be added at the beginning or in the middle of the cases. It will behave just like any other entry point. But in the “default” case, it is entered only when no other case is matched.

 

 

Advantages of using a switch statement over a traditional if-else cascade

 

While it is true that the same functionalities of the switch statement can also be implemented using an if-else cascade, the switch statement allows us in certain situations to write a more clear, compact and readable code.

 

For example, if we wanted to convert our previous example to an if-else cascade, it would look as follows.

 

        String hostingPlan = "Premium";

        System.out.println("Your hosting plan includes:");

        if(hostingPlan.equals("Premium plus")){
            System.out.println("- Extra 1 CPU");
            System.out.println("- Extra 1GB RAM");
            System.out.println("- Unlimited bandwidth");
            System.out.println("- 2 Domain names");
        }else if(hostingPlan.equals("Premium")){
            System.out.println("- Extra 1GB RAM");
            System.out.println("- Unlimited bandwidth");
            System.out.println("- 2 Domain names");
        }else if(hostingPlan.equals("Basic plus")){
            System.out.println("- Unlimited bandwidth");
            System.out.println("- 2 Domain names");
        }else if(hostingPlan.equals("Basic")){
            System.out.println("- 2 Domain names");
        }else {
            System.out.println("Hosting plan not recognized");
        }

    }

 

Notice that we have to perform a lot of code repetition. This is not ideal as if we need to change something, we would have to change it in other places as well. This is error prone and time consuming. For example, if we decide to provide 3 domain names instead of 2, then we will have to update the if-then part of each if statement.

 

Restrictions on switch statements

 

While switch statements can be very efficient and cleaner, they also have certain restrictions. Let us go through these restrictions one by one.

 

Accepted data types to the switch statement input

 

The switch statement will accept the following data types as input:

  • byte
  • short
  • int
  • long
  • char
  • String (only Java version 7 and above)
  • Byte
  • Short
  • Integer
  • Long
  • Enum

 

Unlike if statements and the conditional operator, floating point numbers and other Objects are not allowed to be used inside a switch statement.

 

Configuration restrictions to the switch cases

 

Another restriction that comes to switch statements are the values provided to the case configurations. Each case should be configured with either a constant value or a final value variable. Otherwise, the program will not compile.

The following example is allowed in Java.

        switch (x){

            case 32: //bla bla code here
                     //.....

        }

 

And this is also allowed

 

        final int y = 32;


        switch (x){

            case y: //bla bla code here
                     //.....

        }

 

However, if we remove the final keyword as in the example below, we will get an error that a “constant expression is required”.

 

        //program does not compile
        int y = 32;


        switch (x){

            case y: //bla bla code here
                     //.....

        }

 

 

Another restriction is that while switch statement inputs can be an Object such as Integer, Byte, etc (as mentioned in the previous section), switch cases are more restrictive and allow only primitive data types (int, short, byte, long, char), String and enums. 

 

Summary

 

In this post, we discussed how to use a Java switch statement. We discussed what is the break keyword and how to use it. We also discussed the default keyword and its purpose. We also discussed some of the advantages of using a switch statement over a traditional if-then-else cascade. Finally, we discussed what are the restriction that apply to switch statement inputs and case configurations.

 

If you liked this post or if you have any questions, then please let us know in the comments below and follow us on twitter to be up to date with our latest content 🙂

Java Switch Statements – Uses, Advantages and Restrictions
Scroll to top