Complex “if-then-else” statements are needed when there are many options e.g. consider all the options in a menu.

Fortunately, there is a better way when a lot of options are needed i.e. the “Switch-Case-Break” construct. It works exactly the same as “if-else” but its reader-friendly layout makes it easy to construct and troubleshoot. The switch statement also allows a default branch when the user types an invalid option.

The important thing to know about the Switch case is that all the lines of code will execute one after the other unless there is some means to “break” out of the construct as soon as the condition is met. This is achieved using the keyword “break” or the keyword “return”.

If you also combine “switch” with a “while-loop” you get some robust code that can deal with erratic user input.

NOTES:

  • Switch works with literal values – not variables that can possibly change during runtime.
  • Switch works well with integers, String and char.

Switch-Case with break

Click here for switch with integer and while.

Click here for switch with String

Click here for switch with char

Switch-Case with return

The Java keyword “return” can be used instead of “break” to prevent every line of code executing. In this OOP example called “ActiveRental” we have a user declared template class with properties and methods. The four car rental categories (luxury, standard, economy and SUV) each have their own daily rate. The case statement in the getRate method matches the daily rate to the chosen category (in a much bigger program not shown here)

Click here