Concepts / Introduction to Switch Statements

Introduction to Switch Statements

A switch statement tests one expression and jumps to the case label that matches its value.

  • Programming
Interactive lab

Try it: if / elif / else

How Python tests if / elif conditions from the top, runs only the first true branch, and how and / or stop evaluating as soon as the answer is known (short-circuiting).

How it works

  1. Python evaluates the if condition first.
  2. If it is False, it tries each elif in order; the first True one runs and the rest are skipped without being tested.
  3. If none is True, the else branch runs.
  4. and stops at the first False, or stops at the first True — the right side may never be evaluated.

Default run (5 steps): score = 84; A = 90, B = 80, C = 70. Python tests the conditions from the top. … print(grade) shows B.

Educational simulation

Loading the simulation…

A Decision Made in One Place

Imagine a program that must respond differently to each of several possible values, such as a menu choice or a grade. One approach is a long chain of separate comparisons, each checked in turn. Java offers a different approach: the switch statement. It tests one expression and jumps to the position that matches its value, so the possible positions are listed together in one place.

java

What do you think happens?

Before reading on, decide which line is printed when count holds 2.

  • one

  • two or three

  • other

  • nothing is printed

Reveal answer
Answer:

two or three

The value 2 matches the case label that lists 2 and 3, so control jumps to that entry and its single statement runs. The other entries are not run.

What a Switch Statement Does

Definition

A switch statement tests the value of one expression. Depending on that value, control jumps directly to a particular position inside the switch statement, and the code at that position runs.

Each possible position is marked by a case label. At most one position can be marked as the default, which is used when no case label matches. The arrangement replaces a long chain of separate comparisons with one list of positions, and the value of the expression decides which position is reached.

Running a switch is rarely the hard part. Most of the difficulty lies in reading one. When a switch produces a result you did not expect, the useful question is which position control jumped to, and why that position was chosen. The rest of this article gives you the vocabulary and rules to answer that question yourself.

Expressions a Switch Can Test

A switch statement accepts only expressions of certain types. The expression may be one of the primitive integer types int, short, or byte. It may be the primitive char type. It may be String. It may also be an enum type.

  • int
  • short
  • byte
  • char
  • String
  • an enum type

An enum type is a type whose values are named constants. The source points forward to a later introduction to enum types, so for now it is enough to treat an enum value as one of a fixed set of named choices that a switch can test.

Reading a Case Label

A case label takes the form case followed by a constant list. The constant list contains one or more literals of the same type as the expression, separated by commas. After the label comes the arrow symbol, made of a hyphen and a greater-than character, and then a single statement. That statement may be a subroutine call statement, a throw statement, or a block statement, and a block can contain several nested statements.

casestarts the label2literal of expression type,separates the literals3second literal->arrow symbolprintln statementsingle statement or block
Which parts of the case label are the literal values, and which part is the statement that runs when the label is chosen?
  • The literals in the constant list must all have the same type as the expression in the switch.
  • A switch can have at most one entry labeled default in place of a case label.
  • All case constants must be different from one another.
  • Each arrow entry is followed by exactly one statement, which can be a block that holds several statements.
java
Output
good
Notes on the code
  • The tested expression is a char, so every case literal is a char literal in single quotes.
  • The label case 'B', 'C' matches when grade is B or C.
  • The default entry runs only when no other label matches.

Tracing a Jump Through a Switch

Tracing means following control step by step from the switch expression to the position it reaches. The diagram shows the entries of the first example. The expression is compared against each label in order until a match is found. The matching entry runs its statement, and control then leaves the switch.

countvalue 2case 1print oneafter switchcase 2, 3print two or threedefaultprint othercomparematchesdoes not matchmatchesdoes not matchruns
With count holding 2, which case label does control jump to, which statement runs, and which entries are skipped?
Worked example

Finding the Entry That Runs

Given int count = 2 and the switch shown earlier, which statement runs?

  1. 1
    Identify the expression

    The switch tests count, whose value is 2.

  2. 2
    Check the first label

    case 1 does not match 2, so control moves on to the next label.

  3. 3
    Check the second label

    case 2, 3 contains 2, so this label matches and control jumps to its position.

  4. 4
    Run the matching statement

    The statement after the arrow prints two or three.

  5. 5
    Skip the rest

    The one-statement entries for case 1 and default are not run, and control leaves the switch.

Result

two or three is printed.

Now change the value to 7. No case label contains 7, so no entry matches. The default entry is then the position control jumps to, and the program prints other. This is the point where the unexpected result begins for many readers: they assume a label matched when none did. Checking each label against the value, in order, locates the position reliably.

Two Forms of the Switch Statement

Java has two syntaxes for switch statements. The original syntax was modeled on the C programming language, and the source describes it as error-prone and somewhat awkward to read. It is still common, because a great deal of existing code uses it, so you need to be able to read it. The newer syntax requires Java 17 and improves on the original. The source advises using the new syntax when you write new code. Both forms rest on the same idea: a value selects a jump point, so learning the case label rules helps with either form.

FeatureTraditional syntaxJava 17 syntax
StatusOriginal form modeled on C; described as error-prone and awkwardNewer form and an improvement over the original
AvailabilityStill common because much existing code uses itRequires Java 17
Case formCase labels followed by a colon, as the planning notes describeCase labels followed by an arrow and one statement
Where a case body endsDepends on break statements the programmer placesEnds after the single statement or block following the arrow
Recommended for new codeRead it, but the source advises against writing new code this wayYes, the source advises using it for new code

Traditional and Java 17 switch syntax compared

Because the arrow form attaches exactly one statement or block to each entry, a reader can see where each case body ends without searching for a break. The rest of this article follows the new syntax, and the case label rules described above apply to both forms.

Mistakes With Switch Statements

  • Common mistake

    Switching on a double or float value

    What it looks like
    double price = 2.5; switch (price) { ... }
    Why it fails

    A switch statement never accepts an expression of type double or float.

    Do this instead

    Switch on an int, short, byte, char, String, or enum value instead.

  • Common mistake

    Mixing literal types in one constant list

    What it looks like

    case 'A', 2 -> ... inside a switch on a char

    Why it fails

    The literals in a case label must be the same type as the expression.

    Do this instead

    Keep every literal in the label the same type as the expression, such as char literals for a char expression.

  • Common mistake

    Repeating a case constant

    What it looks like

    case 2 -> ... and later case 2 -> ... in the same switch

    Why it fails

    All case constants must be different.

    Do this instead

    Merge the entries into one label, such as case 2, 3, or give the second value its own distinct constant.

  • Common mistake

    Assuming a result without tracing the labels

    What it looks like

    Guessing that a value of 7 prints two or three

    Why it fails

    Control jumps to a position because its label matches the value. A label that does not contain the value is never chosen.

    Do this instead

    Compare the value with each label in order and identify the entry that matches, or the default if none does.

How an If Statement Chooses a Path

Programs do not always perform every instruction. Sometimes they must choose a path. An if statement creates that choice by examining a boolean-valued expression. The expression is either true or false, and that result determines which action the computer takes. The decision is made at the decision point, and only one of the possible results is carried out for a given run.

temperature > 20boolean expressionprint warmruns when truenext statementprint coolruns when falsetruefalse
When the condition is true, which branch runs and which is skipped? Where do the two paths rejoin?
java
Output
cool
done
Notes on the code
  • temperature > 20 is the boolean expression. With 12 it is false.
  • The false result skips the block before the else and runs the alternative after else.
  • The final line runs on either path, because it follows the whole if-else statement.

Simple If Versus If-Else

An if statement does not always need an else clause. The one-way form, called here a simple if, is useful when the program should perform an action only for a true condition. If the expression is false, the contained statement is skipped and control continues with whatever follows the if statement. An if-else statement, by contrast, always chooses one of two alternatives: exactly one of them executes.

FeatureSimple ifIf-else
Clause after the conditionNo else clauseIncludes an else clause
Number of alternativesOne action, or nothingExactly one of two alternatives
When the condition is falseThe contained statement is skipped and control continues after the ifThe alternative after else runs
When the condition is trueThe contained statement runsThe statement before else runs and the alternative is bypassed

Simple if compared with if-else

java
Output
done
Notes on the code
  • The condition is false, so the only statement inside the simple if is skipped.
  • Control continues with the statement after the if, which prints done.

Tracing Which Statement Runs

When an if statement produces an unexpected result, inspect the decision in order. First identify the boolean expression. Next determine whether its value is true or false. Finally check which statement belongs to that result. In an if-else statement, exactly one alternative executes. In a simple if statement, a false result means the contained action is skipped and execution moves on.

Worked example

Tracing an If-Else with temperature 25

Given int temperature = 25 and the if-else from the previous section, which statement runs and which is skipped?

  1. 1
    Identify the boolean expression

    The expression is temperature > 20.

  2. 2
    Determine its value

    25 is greater than 20, so the expression is true.

  3. 3
    Choose the branch

    The true result selects the statement before else, which prints warm.

  4. 4
    Identify the skipped statement

    The alternative after else, which would print cool, is bypassed.

  5. 5
    Continue after the statement

    Both paths rejoin at the next statement after the if-else.

Result

warm is printed and cool is skipped.

Practice Tracing Both Forms

EASY

Given int code = 3 and the switch below, which line is printed? Work it out from the rules before checking the answer. switch (code) { case 1, 2 -> System.out.println("low"); case 3, 4 -> System.out.println("middle"); default -> System.out.println("high"); }

Hints
  • Identify the value of the expression first.
  • Check the label case 1, 2 and then case 3, 4 in order.
  • The default entry runs only when no label matches.
MEDIUM

Write an if-else statement that prints big when int score is greater than 50 and prints small otherwise. Then state which statement is skipped when score is 80.

Hints
  • The boolean expression is score > 50.
  • The else clause holds the alternative that runs when the expression is false.

Key Takeaways

  • A switch statement tests one expression and jumps to the position whose case label matches its value; at most one default entry handles the no-match case.
  • A switch can test int, short, byte, char, String, or an enum type, but never double or float.
  • Each case label lists one or more same-type literals separated by commas, followed by an arrow and a single statement.
  • An if statement chooses a path by evaluating a boolean expression; an if-else runs exactly one of two alternatives, while a simple if skips its statement when the condition is false.
  • To explain an unexpected result, identify the expression or boolean value, locate the matching label or branch, and then check which statement runs and which is skipped.