Java switch statement

Java switch case is a conditional construct used as a tidier alternative to the if-else construct.

Switch case syntax

Switch(switchExpression){

case constant1:

      case block to execute on matching constant1

case constant2:

      case block to execute on matching constant2

.

.

.

.

case constantN:

      case block to execute on matching constantN

default:

    default block which is executed when none of the constants matches the switchExpression.The default case is optional.

}

Switch case expression legal types

Supported expression types for the switch condition must evaluate to char,byte,short,int,String,enums or wrapper classes Character,Byte,Short,Integer.

The case constants are compile time constants.Class objects/instances cannot be used.

If-else to switch Example

Below is an if-else if-else program:

package devsought.switchcase;

public class IfElseIfElse {

 

    public static void main(String... args) {

 

        String vehicleClass;

        String licenceClass = "E";

        if (licenceClass.contentEquals("A")) {

            vehicleClass = "Scooter";

        } else if (licenceClass.contentEquals("B")) {

            vehicleClass = "scooter and car";

        } else if (licenceClass.contentEquals("C")) {

            vehicleClass = "scooter, car and van";

        } else if (licenceClass.contentEquals("D")) {

            vehicleClass = "scooter, car, van and bus";

        } else if (licenceClass.contentEquals("E")) {

            vehicleClass = "scooter, car, van, bus and truck";

        } else {

            vehicleClass = "Invalid licence class.";

        }

        System.out.println("Licence class " + licenceClass + " can drive vehicles " + vehicleClass);

    }

}

When we run above program,we get below output:

Licence class E can drive vehicles scooter, car, van, bus and truck

Let’s convert the above program to a switch case as below.

package devsought.switchcase;

public class SwitchCaseExample1 {

 

     public static void main(String... args) {

 

        String vehicleClass;

        String licenceClass = "E";

         switch (licenceClass) {

             case "A":

                 vehicleClass = "Scooter";

                 break;

             case "B":

                 vehicleClass = "scooter and car";

                 break;

             case "C":

                 vehicleClass = "scooter, car and van";

                 break;

             case "D":

                 vehicleClass = "scooter, car, van and bus";

                 break;

             case "E":

                 vehicleClass = "scooter, car, van, bus and truck";

                 break;

             default:

                 vehicleClass = "Invalid licence class.";

                 break;

         }

        System.out.println("Licence class " + licenceClass + " can drive vehicles " + vehicleClass);

    }

}

Understanding above program:

The switch (licenceClass) evaluates a string variable licenceClass. The result of evaluation is then matched onto any of the case constants and when a match is found the case block is executed and we get a printed statement of the vehicle classes a given license class is permitted to drive.

**I have misspelled license as licence* in the code examples but that does not affect the functionality of our programs.I am too lazy to correct that now :)

case is for constants not ranges

Unlike if,if-else,if-elseif-else statements whereby we can test ranges ,in switch-case we only test constants .Example the below program will fail to compile.

package devsought.switchcase;

public class SwitchCaseExample2 {

 

    public static void main(String... args) {

        int mark = 50;

        String comment;

        switch (mark) {

            case (mark > 0 && mark < 40):

                comment = "Fail";

                break;

            case (mark > 40 && mark < 55):

                comment = "Pass";

                break;

            case (mark > 55 && mark < 75):

                comment = "Good";

                break;

            case (mark > 75 && mark <= 100):

                comment = "Excellent";

                break;

            default:

                comment = "Invalid mark";

                break;

        }

        System.out.println("Mark =" +mark + ", comment " + comment);

    }

}

The above program will fail compilation with the error ‘incompatible types: boolean cannot be converted to int’.This is because in the case sections,we are testing for a range which evaluates to boolean and a boolean cannot be converted to an int.The primitive typres char,byte and short can be promoted to int but boolean can not.Promotion means that we can assign a short,byte or char to an int variable e.g. int i='k';

default case

The default case is an OPTIONAL case used to specify a block of statements to execute when we don’t have a match of any case constant. It is equivalent to the final else block in if-else construct which is executed after the if and all preceding else-if checks if any have failed to evaluate to true.

In the above program SwitchCaseExample1.java, we use the default case to identity an invalid licenceClass as per the rules of our program.

default:

                 vehicleClass = "Invalid licence class.";

                 break;

Default case location

The default case does not have to be the last case in our switch-case construct.It can be anywhere from the first case to the second last case and it would still work fine.

Example below:

package devsought.switchcase;

public class SwitchCaseExample3 {

 

    public static void main(String... args) {

 

        String vehicleClass;

        String licenceClass = "B";

        switch (licenceClass) {

            default:

                vehicleClass = "Invalid licence class.";

                break;

            case ("A"):

                vehicleClass = "Scooter";

                break;

            case "B":

                vehicleClass = "scooter and car";

                break;

            case "C":

                vehicleClass = "scooter, car and van";

                break;

            case "D":

                vehicleClass = "scooter, car, van and bus";

                break;

            case "E":

                vehicleClass = "scooter, car, van, bus and truck";

                break;

 

        }

        System.out.println("Licence class " + licenceClass + " can drive vehicles " + vehicleClass);

    }

}

Explanation:

On running the above program with licenceClass B,we get output ‘Licence class B can drive vehicles scooter and car’,If we change the licenceClass to BK,we get output ‘Licence class BK can drive vehicles Invalid licence class.’demonstrating that the default case worked well for an invalid licenceClass as expected.This shows the location of the default case is immaterial as its just like any other case though it will execute when none of the cases match.We will however see interesting results on the discussion of break statement below.

break statement & fall-through

Break statement is used to exit a case block execution to prevent subsequent case blocks from executing.We have used it in examples above e.g SwitchCaseExample1.class and SwitchCaseExample3.class.

Let’s see with an example as below what happens in its absence in our switch-case construct.

package devsought.switchcase;

public class SwitchCaseExample4 {

 

    public static void main(String... args) {

 

        String vehicleClass;

        String licenceClass = "B";

        switch (licenceClass) {

            default:

                vehicleClass = "Invalid licence class.";

 

            case ("A"):

                vehicleClass = "Scooter";

 

            case "B":

                vehicleClass = "scooter and car";

 

            case "C":

                vehicleClass = "scooter, car and van";

 

            case "D":

                vehicleClass = "scooter, car, van and bus";

 

            case "E":

                vehicleClass = "scooter, car, van, bus and truck";

 

        }

        System.out.println("Licence class " + licenceClass + " can drive vehicles " + vehicleClass);

    }

}

Running the above program gives output ‘Licence class B can drive vehicles scooter, car, van, bus and truck’ contrary to what we would expect from our business rules of ‘Licence class B can drive vehicles scooter and car’.This implies that cases B,C,D and E were all executed with the variable vehicleClass being assigned a new value in each case block until in case E where the final value which is printed was assigned.This behavior is called fall-through as the execution falls through all case blocks in the absence of a break statement from the first matching case.

If we have an invalid licenceClass like our ‘BK’ case,we get the output ‘Licence class BK can drive vehicles scooter, car, van, bus and truck’ which is erroneous as well since normally we would expect the output ‘Licence class BK can drive vehicles Invalid licence class.’ as per our business rules expectations.In this scenario without the break statement, the default case is just like any other case block and will not function as the fall back block when all other cases fail .

The break in a default case is not necessary as it’s the last case block to be executed.

e.g. the default cases in SwitchCaseExample1.class and SwitchCaseExample3.class can be rewritten as

default:

                 vehicleClass = "Invalid licence class.";

                 

Nested switch-case

Switch-case blocks can be nested .Lets see with below example.

package devsought.switchcase;

enum DriverAge {

    VERY_YOUNG, YOUNG, MIDAGE, SENIOR, OLD

}

 

public class SwitchCaseExample5 {

 

    public static void main(String... args) {

 

        String vehicleClass;

        String licenceClass = "E";

        DriverAge driverAge = DriverAge.VERY_YOUNG;

        switch (licenceClass) {

            case ("A"):

                vehicleClass = "Scooter";

                break;

            case "B":

                vehicleClass = "scooter and car";

                break;

            case "C":

                vehicleClass = "scooter, car and van";

                break;

            case "D":

                vehicleClass = "scooter, car, van and bus";

                switch (driverAge) {

                    case VERY_YOUNG:

                        vehicleClass += ".But a very young driver should be careful driving buses.";

                        break;

                    case OLD:

                        vehicleClass += ".An old driver should not drive buses";

                }

                break;

            case "E":

                vehicleClass = "scooter, car, van, bus and truck";

                switch (driverAge) {

                    case VERY_YOUNG:

                        vehicleClass += ".But a very young driver should be careful driving buses and trucks.";

                        break;

                    case OLD:

                        vehicleClass += ".An old driver should not drive buses and trucks.";

                }

                break;

            default:

                vehicleClass = "Invalid licence class.";

            

        }

        System.out.println("Licence class " + licenceClass + " can drive vehicles " + vehicleClass);

    }

}

Running the program:

We get the output ‘Licence class E can drive vehicles scooter, car, van, bus and truck.But a very young driver should be careful driving buses and trucks.’

This is because our driver is very young as we have set in driverAge and in this case if he holds a class E licence class,he should be very careful when driving buses and trucks.If we change the driverAge to a midage driver,we get ‘Licence class E can drive vehicles scooter, car, van, bus and truck’ as we can trust a mid age driver more than a very young driver,at least as per our business rules.

The programs used in this tutorial can be found on Github.

About the Author - John Kyalo Mbindyo(Bsc Computer Science) is a Senior Application Developer currently working at NCBA Bank Group,Nairobi- Kenya.He is passionate about making programming tutorials and sharing his knowledge with other software engineers across the globe. You can learn more about him and follow him on  Github.