Switch Statement Tutorial - Part 1

This tutorial will introduce you to the basic functionality of the switch statement. The need for a switch statement evolved from several shortcomings of the if statement. The if statement works quite well in situations where the result of an expression will have relatively few outcomes. When things become more complicated, the power of the switch statement comes to the rescue. To demonstrate a simple difference between the two statements, I will create some code that outputs the number days in a month. An argument is passed in from the command line to determine which month we are requesting. First I'll code it using an if-else if-else statement, then I will code it using a switch statement.
A basic switch statement structure looks like this:
switch (expression) {
      case constant1:
            statement(s);
            break;
      case constant2:
            statement(s);
            break;
      case constant3:
            statement(s);
            break;
      more case tests ...
      default:
            statement(s);
            break;
}




Open the command prompt (CMD - see the Getting Started ) and type in the following commands.

C:\Windows\System32>cd \
C:\>md Java
C:\>cd Java
C:\Java>
C:\Java>md SwitchOne
C:\Java>cd SwitchOne
C:\Java\SwitchOne>Notepad SwitchOne.java

Copy and Paste, or type the following code into Notepad and be sure to save the file when you are done.


class SwitchOne {
    public static void main(String args[]) {
        if (args.length != 1) {
            System.out.println("Invalid number of arguments");
            return; // return will terminate execution of the main method
        }

        int numberOfDays = 0;
    
        // don't worry about the .equals yet - I will cover in great detail in a future tutorial
        // for now, just understand that .equals() is checking if args[0] is essentially equal to string literal "month value"
        // The String class is not a primitive data type, it is an object (a special one even then),
        // so different rules apply to the == operator.
        if (args[0].equals("January")) { 
            numberOfDays = 31;			
        } else if (args[0].equals("February")) {
            numberOfDays = 28;			
        } else if (args[0].equals("March")) {
            numberOfDays = 31;			
        } else if (args[0].equals("April")) {
            numberOfDays = 30;			
        } else if (args[0].equals("May")) {
            numberOfDays = 31;			
        } else if (args[0].equals("June")) {
            numberOfDays = 30;			
        } else if (args[0].equals("July")) {
            numberOfDays = 31;			
        } else if (args[0].equals("August")) {
            numberOfDays = 31;			
        } else if (args[0].equals("September")) {
            numberOfDays = 30;			
        } else if (args[0].equals("October")) {
            numberOfDays = 31;			
        } else if (args[0].equals("November")) {
            numberOfDays = 30;			
        } else if (args[0].equals("December")) {
            numberOfDays = 31;			
        } else {
            System.out.println("Invalid month argument. Java is a case sensitive language. Valid months are:");
            System.out.println("January\nFebruary\nMarch\nApril\nMay\nJune");
            System.out.println("July\nAugust\nSeptember\nOctober\nNovember\nDecember");
            return; 
        }

        if (numberOfDays == 28) {
            System.out.println("February has 28 days unless the year is evenly divisible by 4, if so, it has 29 days.");
        } else {
            System.out.println(args[0] + " has " + numberOfDays + " days.");
        }
    }
}

Now switch back to the command prompt (CMD) and type in javac SwitchOne.java and press Enter.
Now type in java SwitchOne March and press Enter.
Try other months for the command line argument.


C:\Java\SwitchOne>javac SwitchOne.java
C:\Java\SwitchOne>java SwitchOne March
March has 31 days.


Now I will do the same thing only with a switch statement this time. Switch back to Notepad, then copy and overwrite the following code, save the file when you are done.


class SwitchOne {
    public static void main(String args[]) {
        if (args.length != 1) {
            System.out.println("Invalid number of arguments");
            return; // return will terminate execution of the main method
        }

        int numberOfDays = 0;
    
        switch(args[0]) {
            case "January":
                numberOfDays = 31;
                break; 
            case "February":
                numberOfDays = 28;
                break; 
            case "March":
                numberOfDays = 31;
                break;
            case "April":
                numberOfDays = 30;
                break;
            case "May":
                numberOfDays = 31;
                break;
            case "June":
                numberOfDays = 30;
                break;
            case "July":
                numberOfDays = 31;
                break;
            case "August":
                numberOfDays = 31;
                break;
            case "September":
                numberOfDays = 30;
                break;
            case "October":
                numberOfDays = 31;
                break;
            case "November":
                numberOfDays = 30;
                break;
            case "December":
                numberOfDays = 31;
                break;
            default: 
                System.out.println("Invalid month argument. Java is a case sensitive language. Valid months are:");
                System.out.println("January\nFebruary\nMarch\nApril\nMay\nJune");
                System.out.println("July\nAugust\nSeptember\nOctober\nNovember\nDecember");
                return; 
                break;
        }

        if (numberOfDays == 28) {
            System.out.println("February has 28 days unless the year is evenly divisible by 4, if so, it has 29 days.");
        } else {
            System.out.println(args[0] + " has " + numberOfDays + " days.");
        }
    }
}

Now switch back to the command prompt (CMD) and type in javac SwitchOne.java and press Enter.
Now type in java SwitchOne March and press Enter.
Try other months for the command line argument.


C:\Java\SwitchOne>javac SwitchOne.java
C:\Java\SwitchOne>java SwitchOne March
March has 31 days.

Final thoughts

When the result of a single expression will determine many outcomes, the switch statement is far superior to the if statement. In my Switch Statement Tutorial - Part 2, I will discuss other powerful features of the switch statement.


Tutorials