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.
Code in GitHub

Get the code for this tutorial using the links below.

Project Repo
Download code for this step
Main class for this step
Dependencies

This is a list of recommended tutorials or courses that might be useful before starting this one.

Contents
Welcome to the Course!
Course Introduction
Chapter 1 - Building Blocks
Quick introduction to Java Variables Classes And Objects Class Example - Defining a class Object Examples - Creating instances Java Application Example - Running our first app Accessing class members - The dot operator Packages - Organizing the code
Chapter 2 - Primitives and Operators
Primitives Arithmetic Operators Assignment Operator Unary Operators Equality and Relational Operators Conditional Operators
Chapter 3 - Statements and Control Flow
Expressions Statements If-Then Statement If-Then-Else Statement More If Statements Switch Statement While and Do-While Statements For Statement Branching Statements Exception Handling
Chapter 4 - Code Example
Example Project - A Simple Vending Machine Adding money Delivering Items Giving Change
Chapter 5 - Classes and Interfaces
Introduction Access Level Modifiers Class Declaration - Class, Methods and Fields Class Declaration - Constructors Inheritance Basics Inheritance - Constructors Inheritance - Methods and Fields Polymorphism Abstract Classes and Methods Interfaces Static Class Members Class Composition Final Classes and Class Members Generic Classes
Chapter 6 - Base Object Behaviors
Introduction Type Comparison Type Casting Object Equality - The Contract Object Equality - Common Pitfalls Object String Representation Garbage Collection Object Comparison Primitive Wrappers and Autoboxing
Chapter 7 - Data Structures
Introduction Arrays - Declaration and Creation Arrays - Basic Operations Core Collection Interfaces List and ArrayList - Basic Operations ArrayList Internals Introduction to Hash Tables Map and HashMap - Basic Operations Set and HashSet - Basic Operations
Chapter 8 - Anonymous classes and lambdas
Introduction Filtering a List Anonymous Classes Lambdas Built-in Functional Interfaces
Chapter 9 - Streams
Introduction Creating Streams Intermediate Operations Terminal Operations