The forgotten feature of Java switch

By xngo on February 24, 2019

When we learned about the switch statement, it is often presented to us as an elegant way to replace if and else if statements.

I, too, overlooked its full potential. Due to my laziness, when I need it, I skim through it quickly to get the syntax to replace my if and else if. I never took the time to fully understand this little statement. It is more than if and else if.

Now, I present you the other side of the switch statement. Its forgotten feature is to handle elegantly the step instructions. Notice that if you remove break; from the case statement, then it is transformed into a step instruction. This can be used in programs to list directions, do incremental database upgrade, etc.

Since I'm the expert at cooking egg, here is how to cook an egg.

public class SwitchFeature {
 
    public static void main(String[] args) {
 
        stepsRemainingToCookAnEgg(3);
    }
    private static void stepsRemainingToCookAnEgg(int step){
        switch(step) {
            case 1: System.out.println("1: Turn on the stove.");
            case 2: System.out.println("2: Put the pan on the stove.");
            case 3: System.out.println("3: Put in the oil.");
            case 4: System.out.println("4: Throw in an egg.");
            case 5: System.out.println("5: Wait for 3 mintues and serve.");
                break;
            default:
                System.out.println("not found");
                break;
        }
    }
}

The output

Since I'm already at step 2: Put the pan on the stove, the remaining steps are:

3: Put in the oil.
4: Throw in an egg.
5: Wait for 3 mintues and serve.

Github

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.