Using switch on Strings in Java

April 10, 2017

In this post, we will learn something about using a switch on String in Java. The way you can do that depends on JDK level you are using.

1. JDK 6 or less

Switch statement works with byte, short, char and int primitive data types. It also works with enumerated types. But it doesn’t work with String. So, there are 2 ways to switch on Strings:

  1. If-then / if-then-else statement
    Output:
    In fact, that is not a switch statement, but it is work with Java 6 or less.
  2. Use enumerated types
    Enum class:
    Example code:
    Output:
    We are forced to use Enum if we want to use a switch statement.
  3. Switch on String directly?
    If we try to use a String directly, a program won’t compile because String is not a compatible type.

2. Since JDK 7

JDK7 introduces the ability to switch on Strings. This makes Java programmers life a bit easier. Nowadays, we can do it like that:

Output:

That’s all.

Click here to add a comment

Leave a comment:


Privacy Preference Center

Necessary

Advertising

Analytics

Other