Switch Statement Tutorial - Part 2

This tutorial will build on the knowledge gained from the Switch Statement Tutorial - Part 1. In that tutorial we learned the basic structure for a switch statement:
switch (expression) {
      case constant1:
            statement(s);
            break;
      more case tests ...
      default:
            statement(s);
            break;
}

The expression must evaluate to a String, byte, char, short, int, or enum. The case constants must be of the same data type as the result of the expression.


Switch statement Fall Through and the Break statement

The switch statement works in a way that you might not expect. Each case constant is evaluated top-down. The first case constant that equals the result of the expression is the entry point and all further statements are executed unless the keyword break occurs.
Consider this code lacking the break statement:
int a = 2;
switch (a) {
      case 1:
            System.out.println(1);
      case 2:
            System.out.println(2);
      case 3:
            System.out.println(3);
      case 4:
            System.out.println(4);
      default:
            System.out.println("default is executed also");
}

The result is:
2
3
4
default is executed also


Why? The reason is that since a == 2, the case 2: test evaluated to true and all subsequent statements are executed as well. As far as Java is concerned, none of the remaining case tests even exist anymore! Didn't I say "the switch statement works in a way that you might not expect"? That's a rhetorical question, don't answer that ;)
So we just learned that the break statement is critical and that it terminates execution of the switch statement at the time it is encountered. Let's make the code above work like we really intended:
int a = 2;
switch (a) {
      case 1:
            System.out.println(1);
            break;
      case 2:
            System.out.println(2);
            break;
      case 3:
            System.out.println(3);
            break;
      case 4:
            System.out.println(4);
            break;
      default:
            System.out.println("default is executed also");
            break;
}

The result is:
2

There are cases where fall-through can create some cool programming effects, however, using fall-through in your programs can create confusion to other programmers reading your code. The same thing rings true when reading code from other programmers. The switch statement should come with a warning - "Beware of the break!". The break statement is such an easy thing to overlook, but just keep in mind what it does and more importantly what happens when it is not there.

The example code for this tutorial is going to take an uppercase letter as a command line argument and display that letter plus all the remaining letters of the alphabet to the console.


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 SwitchTwo
C:\Java>cd SwitchTwo
C:\Java\SwitchTwo>Notepad SwitchTwo.java

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


class SwitchTwo {
    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
        }
   
        switch(args[0]) {
            case "A":
                System.out.print("A");
            case "B":
                System.out.print("B");
            case "C":
                System.out.print("C");
            case "D":
                System.out.print("D");
            case "E":
                System.out.print("E");
            case "F":
                System.out.print("F");
            case "G":
                System.out.print("G");
            case "H":
                System.out.print("H");
            case "I":
                System.out.print("I");
            case "J":
                System.out.print("J");
            case "K":
                System.out.print("K");
            case "L":
                System.out.print("L");
            case "M":
                System.out.print("M");
            case "N":
                System.out.print("N");
            case "O":
                System.out.print("O");
            case "P":
                System.out.print("P");
            case "Q":
                System.out.print("Q");
            case "R":
                System.out.print("R");
            case "S":
                System.out.print("S");
            case "T":
                System.out.print("T");
            case "U":
                System.out.print("U");
            case "V":
                System.out.print("V");
            case "W":
                System.out.print("W");
            case "X":
                System.out.print("X");
            case "Y":
                System.out.print("Y");
            case "Z":
                System.out.print("Z");
                break; // stop execution before default if a valid letter argument was supplied. 

            default: 
                System.out.println("Invalid uppercase letter argument. Java is a case sensitive language.");
        }
    }
}

Now switch back to the command prompt (CMD) and type in javac SwitchTwo.java and press Enter.
Now type in java SwitchTwo R and press Enter.


C:\Java\SwitchTwo>javac SwitchTwo.java
C:\Java\SwitchTwo>java SwitchTwo R
RSTUVWXYZ


Final thoughts

I just want to reiterate a paragraph from above. There are cases where fall-through can create some cool programming effects, however, using fall-through in your programs can create confusion to other programmers reading your code. The same thing rings true when reading code from other programmers. The switch statement should come with a warning - "Beware of the break!". The break statement is such an easy thing to overlook, but just keep in mind what it does and more importantly what happens when it is not there.


Tutorials