Control flow statements – Switch statement

There are similarities between the Switch statement and the if / else if statements but also a decisive difference. Unlike the if / else if statements that test for a condition to be true for every part of the statement, the Switch statement tests only a single value and offers different execution paths depending on its value. That single value can be of the following types:

A wrapper type is an object that holds a primitive type value. As you may know, primitive types are not objects by themselves.

Here’s an example of a switch statement when using an int value. In this example we’re sending in a grade to a method that prints out what the grade means:

As you can see the value is set in the switch statement, and for every path of execution there’s a case statement. There’s no limit of number of lines of code following a case statement, but to keep the code nice and clean it would be better to make a call to another method if there’s a lot of logic to process and place the code there instead. If we would call this method with an int value 5 the output would be:

After the case statements there’s a default statement. This one is executed if no matches can be found among the case statements. The default statement is not mandatory but can be useful in some situations.

At the end of every case statement there’s a statement called break. This exists because we want to end execution if we find a matching value. If we don’t have the break statements the execution will continue for every case statement that follows the matching case statement. So if we remove the break statements above and send in value 3 to the method the output will be:

Every case statement after the one matching 3 is also executed, including the default statement, so it’s very important to have these break statements following the code in the case block, unless a return from the method is made.

Another example below shows a switch statement which tests a String value, name of month, and return the numeric value of it:

When checking strings in a switch statements it’s good practice to convert the string to test to either uppercase or as in the example above lowercase to make it case-insensitive.
Note that in this example we don’t use the break statement. This is because we return the value, and thus exiting the method execution, immediately when we find a match.

Search for more Java info on this site here:
Custom Search

Any thoughts or questions?