Java Switch Statement | Switch Case Multiple Values example

Java switch statement is matched case(condition) and execute statement for that. In the Switch statement, using passing value and then this value will go down the list of the case to find matched one. If There is not matched then it will return the default statement.

When you are using an if-else condition statement, it will become longer, So you can use a switch statement instead of it.

Java Switch Statement | Switch Case Multiple Values example

This Tutorial you will learn about What is and How to use switch case in java.


Here is java switch statement syntax:

Switch Statement Flow Diagram:

Look at the flow diagram, how switch cases work.

Here is java switch statement syntax

Java switch Example

A simple example of the switch statement, where declaring variables with values and pass in switch express. If anyone of the case is matched then it will print the matched statement otherwise default value. A break keyword is required to stop code on the case.

Output: Value 2

Java Switch Statement with String

You have seems upper example has based used int values, now look at how to use a Switch statement with string.

Output: Well done

Switch case multiple values

What if you want a check multiple value check for single statement? Here is Java switch case multiple values example.

Complete example:

Output: Value 1
Value 2

QA: What if you don’t use a break keyword in a switch case statement?

In this situation not using break keyword then Java switch statement is fall-through. It means it will execute all statements after the first case match. See this example after matched case 2: all the statement is executed and printed.

Output: Value 2
Value 3
Not in 1, 2 or 3

QA: What if 2 case unit value is the same?

In this case, the compiler will throw an Error:(14, 13) java: duplicate case label

Here is an example for the same.

Output Screenshot: 

Java Switch Statement error

Some Notes :

Here is some important point of the switch statement in Java, have to follow.

  • You can use N number of case values for a switch expression.
  • The Case unit must be unique, otherwise, a compile-time error occurred.
  • Variables are not allowed in case unit
  • The default case is optional.

Do comment if you have any doubts and suggestions on this tutorial.

Note: This example (Project) is developed in IntelliJ IDEA 2018.2.6 (Community Edition)
JRE: 11.0.1
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.14.1

Java version 11

All Java Switch statement Examples are in Java 11, so it may change on different from Java 9 or 10 or upgraded versions.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.