Chapter 3 - Java for Beginners Course

Switch Statement

An additional conditional operator is the switch statement that selects the code to execute based on the value of a given expression.

The expression can be an integer (byte, short, char and int data types), a String value or an enumerated (Enum) value. The last one we haven’t covered yet in this course.

The syntax of a switch statement looks as follows:

switch(expressionToEvaluate) {
	case value1:
		// next line of code to execute if the expression equals value1
	case value2:
		// next line of code to execute if the expression equals value2
	//...
	case valueN:
		// next line of code to execute if the expression equals valueN
	default:
		// next line of code to execute if the expression isn't equal to any of the case labels
}

The code inside the braces of the switch statement is called a switch block, and contains zero of more case labels and an optional default label.

Java will evaluate the expression of the switch statement (expressionToEvaluate) and will compare its value to the ones provided in the case labels. This can have 2 outcomes:

  1. If it matches one of the case labels, the execution will continue from that point and the code of the previous case labels will not be evaluated. The code of the case labels and default label (if any) that follow will be executed unless we add a break clause (we’ll discuss that below).

  2. If it doesn’t match any of the labels, then the code will continue from the default label (if provided).

The default label doesn’t need to be the last one in the list, Java doesn’t enforce this.
Two cases can’t have the same value, they must be unique.

For example, the following code translates a numeric value into a human readable message for a (hypothetical) heating power setting:

// 0 -> Off, 1 -> Low, 2-> High
int heatingPower = 1;
String messageToDisplay;

switch (heatingPower) {
    case 0:
        messageToDisplay = "Off";
        break;
    case 1:
        messageToDisplay = "Low";
        break;
    case 2:
        messageToDisplay = "High";
        break;
    default:
        messageToDisplay = "Invalid code!";
        break;
}

System.out.println("The heating is set to: " + messageToDisplay);

Output:

The heating is set to: Low

Analysing the switch statement example

In our example above, the expression of the switch statement is the heatingPower variable that has a value of 1.

As we have a case label that matches this value, the execution will proceed from that point, meaning that the messageToDisplay = "Low"; statement will be the next line of code to be executed.

The next line after it is a break statement, that causes a termination of the switch statement, hence, the rest of the code below (case 2 onwards) won’t be executed. Java resumes execution at the next line after the switch block, in our case, we print the message The heating is set to: Low.

To break or not to break

In the example above, we made use of the break statement, however, this is optional and should be used when required.

The use of break statements inside the switch statement depends on the case you have at hand. It is completely optional.
You can use break statements in some case labels and not in others, again, it depends on your use case.

Let’s analyse a similar example that doesn’t make use of the break statement.

In this case, we want to print out the available heating options above a certain minimum level, specified by the minHeatingPower variable.

int minHeatingPower = 1;
String availablePowerOptions = "";

switch (minHeatingPower) {
    case 0:
        availablePowerOptions += "Off ";
    case 1:
        availablePowerOptions += "Low ";
    case 2:
        availablePowerOptions += "High";
}

System.out.println("The available heating options above the given minimum are: " + availablePowerOptions);

Output:

The available heating options above the given minimum are: Low High

Analysing the second switch statement example

Similar to our first example, we have a value of 1 for our switch statement expression, and we have a case label that matches that value.

This means that the execution will proceed from the case 1 onwards. Note though, that the code below the case 2 label is also executed. As we don’t have a break statement, the code inside the switch block continues executing as per the definition of the switch statement.

This is known as fall through, the statements continue executing regardless of the value of the next case labels. If we don’t want our code to fall through other case labels, we need to use a break statement.

As a result, our availablePowerOptions variable ends up with a value of "Low High".

Should I use an if or a switch?

As with the break clause, it depends on the use case you have at hand. If using a switch statement is more readable and you’re testing an expression against a specific set of values, then you might want to use or consider using a switch statement.

Similar to if statements, switch blocks with too many cases or with very complex logic inside of them can indicate a Code Smell.