Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Switch on String in Java: Syntax, Behavior, and Pitfalls

Learn how switch on String works in Java, covering equality semantics, null handling, case sensitivity, performance, and Java 14 switch expressions.

~4 min readJava
#Java#Switch Statements#String Handling#Control Flow
Illustration of a Java switch statement routing string values to different code branches

A switch statement on String has been available since Java 7, but its behavior differs from primitive and enum switches in ways that still catch developers off guard. The comparison uses equals() rather than reference equality, a null input throws NullPointerException immediately, and case labels must be compile-time constant strings. These constraints shape how you write, test, and maintain switch statements on String.

Basic Syntax of switch on String

The standard form of a String switch uses the same colon syntax as switches on primitives or enums:

java
String status = "active"; switch (status) { case "active": System.out.println("Processing active account"); break; case "pending": System.out.println("Waiting for confirmation"); break; case "closed": System.out.println("Account closed"); break; default: System.out.println("Unknown status"); break; }

Each case label must be a constant expression whose type is String. A final variable initialized with a string literal is allowed, but a variable whose value is determined at runtime is not. The compiler needs the constant values at compile time to build the dispatch structure.

How String Comparison Works Inside switch

The switch statement on String does not use reference equality. Matching is value-based: a case matches when the switch expression's value is equal to the case label's value according to equals(). This is a critical difference from ==, which compares object references.

java
String value = new String("active"); switch (value) { case "active": // This branch executes because equals() is used break; }

The object stored in value is not the same reference as the literal "active", so an if-else chain using == would not match. That mismatch is a common source of bugs when developers convert if-else chains to switch statements.

Null Handling and the NullPointerException Risk

A switch statement on a null String throws a NullPointerException immediately, before any case is evaluated. Because the switch expression is dereferenced during matching, null cannot pass through.

java
String input = null; // Throws NullPointerException switch (input) { case "a": break; default: break; }

If your input can be null, check it before the switch:

java
if (input == null) { // handle null case explicitly return; } switch (input) { // safe to switch here }

This is a behavioral difference from if-else chains, where a null check can be part of the condition. The switch statement gives you no way to catch null inside the case labels, so the guard must come first.

Case Sensitivity and Input Normalization

String switch is case-sensitive, because String.equals() is case-sensitive. The value "Active" does not match the case label "active". If your input comes from user entry, configuration files, or external APIs, you should normalize the string before switching.

java
String input = rawInput.toLowerCase(Locale.ROOT); switch (input) { case "active": break; case "pending": break; }

Using Locale.ROOT avoids locale-dependent case mapping, which differs in Turkish and a few other locales. After normalization, all case labels must use the same casing convention.

Performance Behavior of String switch

For a String switch with multiple case labels, javac typically does not compile it into a simple linear scan through every case label. A common translation computes the hash code of the switch expression once, uses that hash to narrow the possible case labels, and then calls equals() to confirm a candidate match.

The result is that a String switch with many cases is usually faster than an equivalent if-else chain that calls equals() repeatedly until a match is found. For a small number of cases, the difference is negligible, and readability should drive the choice.

One practical consequence: because the compiler builds the dispatch structure from values known at compile time, case labels must be constant strings. A runtime-computed string cannot be used as a case label.

Switch Expressions for Cleaner Value Assignment

Switch expressions became a standard feature in Java 14. The arrow syntax avoids the fall-through problem entirely and allows a switch to produce a value directly.

java
String status = "active"; int priority = switch (status) { case "active" -> 1; case "pending" -> 2; case "closed" -> 3; default -> 0; };

The arrow form does not require break. Each branch produces a value, and the yield keyword can be used for multi-statement branches:

java
int priority = switch (status) { case "active" -> { logAccess(status); yield 1; } default -> 0; };

Switch expressions work with String the same way as switch statements. The same equality, null, and case-sensitivity rules apply. The main gain is that value assignment is more compact and the compiler enforces exhaustiveness when the switch is used as an expression.

Choosing Between switch and if-else Chains

Switch on String is the right choice when you are matching exact values against a known set of literals. The syntax is more readable than a long if-else chain, and the hash-based dispatch is more efficient for many cases.

If-else is better when the condition is not exact equality. For example, startsWith(), contains(), regex matching, or combined conditions require if-else. Switch cannot express these.

java
if (status.startsWith("active_")) { // prefix matching, cannot be a switch case } else if (status.contains("error")) { // substring matching, cannot be a switch case }

Use switch when the set of possible values is fixed and known at compile time. Use if-else when the matching logic is dynamic or involves pattern-based conditions.

Common Pitfalls and Their Causes

Forgetting break in the traditional colon syntax causes fall-through, where execution continues into the next case. This is the most common bug when converting an if-else chain to a switch. The arrow syntax eliminates this class of error.

Case labels must be constant strings. A final variable initialized with a string literal can be used, but a variable initialized at runtime cannot. This constraint exists because the compiler builds the dispatch table at compile time.

The default branch is optional in a switch statement but required in a switch expression when the compiler cannot prove exhaustiveness. For String switch, the compiler cannot prove that every possible string is covered, so the default branch is effectively required in switch expressions.

Try matching browser tools

All tools

Small utilities that fit Java work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Java guides

More in Java

All Java guides

The guides filed next to this one in Java, in library order.