Switch statement in Java: alternative to the else if statement


Keywords: switch statement, else if statement, conditional statements

if else statement Java

The final article in this chapter on the conditional statements will look at the switch statement that is a multi-way branch statement. The switch statement executes one or several code blocks, similar to the else if statement, depending on which of its so-called case statements are true.

What is the switch statement in Java?

The switch statement executes one or several code blocks, similar to the else if statement, depending on which of its so-called case statements are true. Simply put, the switch states enables us to execute specific code blocks depending on if a given condition is true. We can do the same functionality using the else if statement in Java.

How the switch statement in Java works?

A switch statement can be described as a compact version of the if statement and is useful when determining between a specific number of operations. In summary, the switch statement works as follows:

  • The switch statement is an alternative to the if statement when you have a multiple-choice situation.
  • A switch statement controls an expression that must be of data types, such as integer, char, or String.
  • Therefore, it is not possible to use the data types long, float, double or Boolean in the switch case expression.

If we illustrate the switch statement with a flow chart

Switch statement Java programming

Figure 1: Switch statement in Java

How to create switch statement in Java?

  • The switch statement is created using the reserved word switch followed by an expression in parentheses ( ).
  • All options are then specified with the reserved word case followed by the operations the program should perform if the case statement has the same value as the switch statement’s expression.
  • A case statement ends with the reserved word break.
  • Finally, a switch statement ends with a default expression that is created with the reserved word default. The default expression states what happens if none of the case statements is true, similar to the else statement.

Syntax: Declaring switch statement in Java

Let’s use the steps and enter it in the code editor:

switch (expression){

   case 1:
      // code block for case 1
      break;
   
   case 2:
      // code block for case 2
      break;

   case 3:
      // code block for case 3 
      break;
   .
   .
   .
   default:
      // code block for default expression
      break;
}

Examples: Switch statement in Java

Let’s use what we have learnt and look at two examples of creating and using a switch statement.

Example 1: Switch statement compared with else if statement to convert shoe sizes

In this example, we will code a program that, given a shoe size for men’s shoes according to US size, prints the corresponding size according to EU size. For example, US size 9 is the same as EU size 42. We do not include all sizes as there will be a lot to write in this case, but only to show similarities and differences between a switch statement and the else if statement. Furthermore, if you want to see a table of corresponding sizes, you can find it here: Shoe Size Conversion Chart.

Switch statement

public class Example{
   public static void main(String[] args) {
      
      int usSize = 9;

      switch (usSize){

         case 6:
            System.out.println("The EU size is: 39");
            break;

         case 7:
            System.out.println("The EU size is: 40");
            break;

         case 8:
            System.out.println("The EU size is: 41");
            break;

         case 9:
            System.out.println("The EU size is: 42");
            break;

         case 10:
            System.out.println("The EU size is: 43");
            break;

         case 11:
            System.out.println("The EU size is: 44");
            break;

         case 12:
            System.out.println("The EU size is: 45");
            break;

         default:
            System.out.println("Did not find the size");
            break;
      }
   }
}

Else if statement

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

      int usSize = 9;

      if(usSize == 6){
         System.out.println("The EU size is: 39");
      }

      else if(usSize == 7){
         System.out.println("The EU size is: 40");
      }

      else if(usSize == 8){
         System.out.println("The EU size is: 41");
      }

      else if(usSize == 9){
         System.out.println("The EU size is: 42");
      }

      else if(usSize == 10){
         System.out.println("The EU size is: 43");
      }

      else if(usSize == 11){
         System.out.println("The EU size is: 44");
      }

      else if(usSize == 12){
         System.out.println("The EU size is: 45");
      }

      else {
         System.out.println("Did not find the size");
      }
   }
}

In both cases, we get the result

The EU size is: 42

In the example, we see that the switch statement and the else if statement are similar to each other and which one you choose is based on preference.

Example 2: Declare a switch statement that verify the input from the user

Furthermore, let’s look at one example that receives in information from the user and then based on the input prints a text. We will use the built-in class Scanner to receive input from the user.

// Imports the Scanner class
import java.util.Scanner;

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

            // Ask the user to enter info.
            System.out.println("Write the letter between a - d " +
                    "that you want to print in uppercase" +
                    "Note, lowercase only");

            // Creates a scanner object
            Scanner sc = new Scanner(System.in);

            // Returns the next character from the scanner
            String userInput = sc.next();

            // Creates the switch statement
            switch (userInput){

            // Declares different cases
                case "a":
                    System.out.println("The user entered input: " 
                            + "A");
                    break;

                case "b":
                    System.out.println("The user entered input: " 
                            + "B");
                    break;

                case "c":
                    System.out.println("The user entered input: " 
                            + "C");
                    break;

                case "d":
                    System.out.println("The user entered input: "
                            + "D");
                    break;

            // If the user does not enter a valid input
                default:
                    System.out.println("Invalid input");
                    break;

            }
        }
}

Difference between switch statement and else if statement?

Both the switch statement and the else if statement accomplish the same functions. Some claim that a switch statement provides a more elegant and compact code, but it is a matter of preference and personal opinion. Furthermore, there are also indications that a switch statement is faster at execution than the else if statement. If a switch statement contains more than five objects, it is implemented with a lookup table or a hash list. This means that all objects have the same access time compared to a list of ifs where the last object takes much more time to reach because it must first evaluate each previous state.

However, it should be mentioned that it will probably not significantly impact your program’s performance, which of the switch statement and else if statement you decide to use. Finally, customize the solution and use the features you feel most comfortable with and best suit your program. There is no clear answer as to which of the switch statement and the else if statement is best, as it depends on numerous factors that must be evaluated on a case-by-case basis.

Summary: Switch statement in Java

The switch statement executes one or several code blocks, similar to the else if statement, depending on which of its so-called case statements are true.

  • The switch statement is an alternative to the if statement when you have a multiple-choice task.
  • The conditional statements enable us to control the logic of our program
  • A switch statement controls an expression that must be of data types, such as integer, char, or String. Therefore, it is not possible to use the data types long, float, double or Boolean in the switch case expression.

Syntax: Declaring switch statement

switch (expression){

   case 1:
      // code block for case 1
      break;
   
   case 2:
      // code block for case 2
      break;

   case 3:
      // code block for case 3 
      break;
   .
   .
   .
   default:
      // code block for default expression
      break;
}

FAQ: Switch statement

When to use the switch statement?

The switch statement is an alternative to the conditional statements (the if, the else, and the else if statement) when you have a multiple choice situation.

How to create switch statement in Java?

The switch statement is created using the reserved word switch, followed by an expression in parentheses (). All options are then specified with the reserved word case followed by the operations the program should perform if the case statement has the same value as the switch statement’s expression. A case statement ends with the reserved word break.
Finally, a switch statement ends with a default expression that is created with the reserved word default. The default expression states what happens if none of the case statements is true, similar to the else statement.

Is the switch statement better than the else if statement?

Both the switch statement and the else if set fulfil the same purposes. Use the features that you feel most comfortable with and that best suit your program. There is no clear answer as to which of the switch statements and else if statements are the best, and the differences between them are relatively small.