Understanding Java Switch Statement - Control flow statement

Understanding Java Switch Statement - Control flow statement

Have you controlled a bulb with an on-and-off switch? You might even have played with it before. Imagine the logic behind it when you press it and it switches on the bulb or you use the switch to switch it off. Another case is if there's no switch, well that's not possible.

In this article, we'll consider how the switch works in Java programming language. Have you ever thought of when you should use the "Switch" statements? Let's dive in.

What is the Java Switch statement?

In Java, the switch statement is a control flow statement used for decision-making based on the value of a variable or an expression. The switch statement evaluates the expression or variable once and then compares it to multiple case values. Each case represents a possible value or condition that the expression can match. Isn’t that complex, right? In the case of the bulb we mentioned earlier, it’s just like when you tell the switch that when it is in value”1” it should switch on the bulb but if it’s in value “2” then the bulb should turn off.

Switch statement

A very good example of the switch statement is:

switch ( expression ) {

    case-label-or-default -> statement 

    case-label-or-default -> statement 

    case-label-or-default -> statement

}

The "switch" declaration signals that we're about to use a switch statement, followed by a parenthesis that will take an expression. Now, we have the body of the switch, which contains all the cases we're trying to cover and what should happen if the cases match.

Let's go through how your bulb switch might work

private static final int N = 3;

switch ( N ) { 

case 1 -> System.out.println(“Turns on the light”);

case 2 -> System.out.println("Truns off the light.");

}

Initially, I have to define my variable which is the N. For us to be able to use the switch statement we need the keyword “switch” This denotes the start of the switch statement followed by the expression which is the N (the variable) then we have the body of the switch. Now we’ll test the expression against the cases we have and the first case is if N is 1 then we’ll have our bulb turned on otherwise if it is 2 then it will turn it off. Boom! We’ve controlled our light.

In the switch statements we have what is called the default case which means if none of the cases match the expression then we’ll have to run the statement. Also, we can use a block statement instead of a single statement by using {} after the ->. We’ll see an example below.

public static void convertToInches() {
        Scanner myObj = new Scanner(System.in);

        int optionNumber;   // Option number from menu, selected by user.
        double measurement; // A numerical measurement, input by the user.
                            //    The unit of measurement depends on which
                            //    option the user has selected.
        double inches;      // The same measurement, converted into inches.

        /* Display menu of options, and get user's selected option number. */

        System.out.println("""
                What unit of measurement does your input use?

                        1. inches
                        2. feet
                        3. yards
                        4. miles

                Enter the number of your choice:
                """);

        optionNumber = Integer.parseInt(myObj.nextLine());

        /* Read user's measurement and convert to inches. */

        switch ( optionNumber ) {
           case 1 -> {
               System.out.println("Enter the number of inches: ");
               measurement = Integer.parseInt(myObj.nextLine());
               inches = measurement;
               System.out.println(measurement + " in inches " + "to Inches is " + inches);
               break;
           }
           case 2 -> {
               System.out.println("Enter the number of feet: ");
               measurement = Integer.parseInt(myObj.nextLine());
               inches = measurement * 12;
               System.out.println(measurement + " in feet " + "to Inches is " + inches);
               break;
           }
           case 3 -> {
               System.out.println("Enter the number of yards: ");
               measurement = Integer.parseInt(myObj.nextLine());
               inches = measurement * 36;
               System.out.println(measurement + " in yard " + "to Inches is " + inches);
               break;
           }
           case 4 -> {
               System.out.println("Enter the number of miles: ");
               measurement = Integer.parseInt(myObj.nextLine());
               inches = measurement * 12 * 5280;
               System.out.println(measurement + " in miles " + "to Inches is " + inches);
               break;
            }
           default -> {
               System.out.println("Error!  Illegal option number!  I quit!");
               System.exit(1);
           }

        } // end switch
    }

That’s a lengthy code, right? I know that too. We’ll break it down here. The first (myObj) variable we have is for our reading of data from the console which is called a scanner. Then we have our optionNumber (the options the user selected) while we also have the measurement and the inches in which the measurement is the calculation (conversion) and the inches is the final conversion or result.

We initialized our optionNumber by taking the user input and converting it to an Integer for us to be able to use it to carry out some computation. Here comes where the switch comes in, the switch compares the selected option and carries out the task assigned to it. Assuming the user selected 4 which means the person is converting from miles to inches then the switch sees that the case matches case 4 and executes the block statement and carries out the calculations. When a match is found, the code block associated with that case is executed until a break statement is encountered, which exits the switch statement.

When to use the switch statement

Use the switch statement when:

  • Dealing with a single variable or expression that needs to be compared against a fixed set of values.

  • Handling a large number of possible cases or values.

  • The code blocks associated with each case are relatively simple and do not require complex conditions.

It's important to note that the switch statement has some limitations. It can only be used with certain data types (e.g., byte, short, int, char, or enumerated types) and cannot handle floating-point numbers or boolean values directly.

Conclusion

In conclusion, the switch statement in Java provides a concise and efficient way to handle decision-making based on the value of a variable or expression. It is particularly useful when dealing with a single variable that needs to be compared against a fixed set of values or when there are a large number of possible cases or values to handle. The code blocks associated with each case are relatively simple and do not require complex conditions, making the switch statement an appropriate choice.

Understanding the switch statement and its appropriate usage can enhance your ability to write clean and organized code. By leveraging this powerful control flow statement, you can efficiently handle different scenarios and make your code more robust and maintainable.