• Java Arrays
  • Java Strings
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Spring Boot
  • Variable Arguments (Varargs) in Java
  • Java Array Exercise
  • ThreadFactory Interface in Java with Examples
  • Scanner and nextChar() in Java
  • Java 8 Predicate with Examples
  • Private Constructors and Singleton Classes in Java
  • Java.util.zip.InflaterOutputStream class in Java
  • What is SAX in XML?
  • Static vs Dynamic Binding in Java
  • Type conversion in Java with Examples
  • Semaphore in Java
  • enum in Java
  • The Initializer Block in Java
  • Type Erasure in Java
  • Valid variants of main() in Java
  • Java Networking
  • Blank Final in Java
  • Using actionPerformed from Another Java Class
  • final, finally and finalize in Java

Switch Statements in Java

The switch statement in Java is a multi-way branch statement. In simple words, the Java switch statement executes one statement from multiple conditions.

It is like an if-else-if ladder statement. It provides an easy way to dispatch execution to different parts of code based on the value of the expression. The expression can be a byte , short , char , or int primitive data type. It tests the equality of variables against multiple values.

Note: Java switch expression must be of byte, short, int, long(with its Wrapper type), enums and string. Beginning with JDK7, it also works with enumerated types ( Enums in java), the String class, and Wrapper classes.

Size Printer Example

Some Important Rules for Java Switch Statements

  • There can be any number of cases just imposing condition check but remember duplicate case/s values are not allowed.
  • The value for a case must be of the same data type as the variable in the switch.
  • The value for a case must be constant or literal. Variables are not allowed.
  • The break statement is used inside the switch to terminate a statement sequence.
  • The break statement is optional. If omitted, execution will continue on into the next case.
  • The default statement is optional and can appear anywhere inside the switch block. In case, if it is not at the end, then a break statement must be kept after the default statement to omit the execution of the next case statement.

Flowchart of Switch-Case Statement 

This flowchart shows the control flow and working of switch statements:

switch-statement-flowchart-in-java

Note: Java switch statement is a fall through statement that means it executes all statements if break keyword is not used, so it is highly essential to use break keyword inside each case.  

Example: Finding Day

Consider the following Java program, it declares an int named day whose value represents a day(1-7). The code displays the name of the day, based on the value of the day, using the switch statement.

break in switch case Statements

A break statement is optional. If we omit the break, execution will continue into the next case. 

It is sometimes desirable to have multiple cases without “ break ” statements between them. For instance, let us consider the updated version of the above program, it also displays whether a day is a weekday or a weekend day.

Switch statement program without multiple breaks

Java Nested Switch Statements

We can use a switch as part of the statement sequence of an outer switch. This is called a nested switch . Since a switch statement defines its block, no conflicts arise between the case constants in the inner switch and those in the outer switch.

Nested Switch Statement

Java Enum in Switch Statement

Enumerations (enums) are a powerful and clear way to represent a fixed set of named constants in Java. 

Enums are used in Switch statements due to their type safety and readability.

Use of Enum in Switch

default statement in Java Switch Case

default case in the Switch case specifies what code to run if no case matches.

It is preferred to write the default case at the end of all possible cases, but it can be written at any place in switch statements.

Writing default in the middle of switch statements:

Writing default in starting of switch statements

Case label variations

Case label and switch arguments can be a constant expression. The switch argument can be a variable expression.

Using variable switch arguement.

A case label cannot be a variable or variable expression. It must be a constant expression.

Java Wrapper in Switch Statements

Java provides four wrapper classes to use: Integer, Short, Byte, and Long in switch statements.

Java Wrapper in switch case.

Read More: Usage of Enum and Switch Keyword in Java String in Switch Case in Java Java Tutorial 

To practice Java switch statements you can visit the page: Java Switch Case statement Practice

Switch statements in Java are control flow structures, that allow you to execute certain block of code based on the value of a single expression. They can be considered as an alternative to if-else-if statements in programming.

Java Switch Statements- FAQs

How to use switch statements in java.

To use switch statement in Java, you can use the following syntax: switch (expression) {    case value1:        // code to execute if expression equals value1        break;    case value2:        // code to execute if expression equals value2        break;    // … more cases    default:        // code to execute if none of the above cases match }  

Can we pass null to a switch

No, you can not pass NULL to a switch statement as they require constant expression in its case.

Can you return to a switch statement

No, switch statements build a control flow in the program, so it can not go back after exiting a switch case.

Please Login to comment...

Similar reads.

  • How to Use ChatGPT with Bing for Free?
  • 7 Best Movavi Video Editor Alternatives in 2024
  • How to Edit Comment on Instagram
  • 10 Best AI Grammar Checkers and Rewording Tools
  • 30 OOPs Interview Questions and Answers (2024)

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Java Tutorial

Java methods, java classes, java file handling, java how to, java reference, java examples, java switch, java switch statements.

Instead of writing many if..else statements, you can use the switch statement.

The switch statement selects one of many code blocks to be executed:

This is how it works:

  • The switch expression is evaluated once.
  • The value of the expression is compared with the values of each case .
  • If there is a match, the associated block of code is executed.
  • The break and default keywords are optional, and will be described later in this chapter

The example below uses the weekday number to calculate the weekday name:

Try it Yourself »

The break Keyword

When Java reaches a break keyword, it breaks out of the switch block.

This will stop the execution of more code and case testing inside the block.

When a match is found, and the job is done, it's time for a break. There is no need for more testing.

A break can save a lot of execution time because it "ignores" the execution of all the rest of the code in the switch block.

Advertisement

The default Keyword

The default keyword specifies some code to run if there is no case match:

Note that if the default statement is used as the last statement in a switch block, it does not need a break.

Test Yourself With Exercises

Insert the missing parts to complete the following switch statement.

Start the Exercise

Get Certified

COLOR PICKER

colorpicker

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

[email protected]

Top Tutorials

Top references, top examples, get certified.

Learn Java practically and Get Certified .

Popular Tutorials

Popular examples, reference materials, learn java interactively, java introduction.

  • Java Hello World
  • Java JVM, JRE and JDK
  • Java Variables and Literals
  • Java Data Types
  • Java Operators
  • Java Input and Output
  • Java Expressions & Blocks
  • Java Comment

Java Flow Control

  • Java if...else

Java switch Statement

  • Java for Loop
  • Java for-each Loop
  • Java while Loop

Java break Statement

Java continue Statement

  • Java Arrays
  • Multidimensional Array
  • Java Copy Array

Java OOP (I)

  • Java Class and Objects
  • Java Methods
  • Java Method Overloading
  • Java Constructor
  • Java Strings
  • Java Access Modifiers
  • Java this keyword
  • Java final keyword
  • Java Recursion
  • Java instanceof Operator

Java OOP (II)

  • Java Inheritance
  • Java Method Overriding
  • Java super Keyword
  • Abstract Class & Method
  • Java Interfaces
  • Java Polymorphism
  • Java Encapsulation

Java OOP (III)

  • Nested & Inner Class
  • Java Static Class
  • Java Anonymous Class
  • Java Singleton
  • Java enum Class
  • Java enum Constructor
  • Java enum String
  • Java Reflection
  • Java Exception Handling
  • Java Exceptions
  • Java try...catch
  • Java throw and throws
  • Java catch Multiple Exceptions
  • Java try-with-resources
  • Java Annotations
  • Java Annotation Types
  • Java Logging

Java Assertions

  • Java Collections Framework
  • Java Collection Interface
  • Java List Interface
  • Java ArrayList
  • Java Vector
  • Java Queue Interface
  • Java PriorityQueue
  • Java Deque Interface
  • Java LinkedList
  • Java ArrayDeque
  • Java BlockingQueue Interface
  • Java ArrayBlockingQueue
  • Java LinkedBlockingQueue
  • Java Map Interface
  • Java HashMap
  • Java LinkedHashMap
  • Java WeakHashMap
  • Java EnumMap
  • Java SortedMap Interface
  • Java NavigableMap Interface
  • Java TreeMap
  • Java ConcurrentMap Interface
  • Java ConcurrentHashMap
  • Java Set Interface
  • Java HashSet
  • Java EnumSet
  • Java LinkedhashSet
  • Java SortedSet Interface
  • Java NavigableSet Interface
  • Java TreeSet
  • Java Algorithms
  • Java Iterator
  • Java ListIterator
  • Java I/O Streams
  • Java InputStream
  • Java OutputStream
  • Java FileInputStream
  • Java FileOutputStream
  • Java ByteArrayInputStream
  • Java ByteArrayOutputStream
  • Java ObjectInputStream
  • Java ObjectOutputStream
  • Java BufferedInputStream
  • Java BufferedOutputStream
  • Java PrintStream

Java Reader/Writer

  • Java Reader
  • Java Writer
  • Java InputStreamReader
  • Java OutputStreamWriter
  • Java FileReader
  • Java FileWriter
  • Java BufferedReader
  • Java BufferedWriter
  • Java StringReader
  • Java StringWriter
  • Java PrintWriter

Additional Topics

  • Java Scanner Class
  • Java Type Casting
  • Java autoboxing and unboxing
  • Java Lambda Expression
  • Java Generics
  • Java File Class
  • Java Wrapper Class
  • Java Command Line Arguments

Java Tutorials

  • Java if...else Statement
  • Nested Loop in Java

The switch statement allows us to execute a block of code among many alternatives.

How does the switch-case statement work?

The expression is evaluated once and compared with the values of each case.

  • If expression matches with value1 , the code of case value1 are executed. Similarly, the code of case value2 is executed if expression matches with value2
  • If there is no match, the code of the default case is executed

Note : The working of the switch-case statement is similar to the Java if...else...if ladder . However, the syntax of the switch statement is cleaner and much easier to read and write.

Example: Java switch Statement

In the above example, we have used the switch statement to find the size. Here, we have a variable number . The variable is compared with the value of each case statement.

Since the value matches with 44 , the code of case 44 is executed.

Here, the size variable is assigned with the value Large .

  • Create a Simple Calculator Using the Java switch Statement

Flowchart of switch Statement

Flowchart of the Java switch statement

break Statement in Java switch...case

Notice that we have been using break in each case block.

The break statement is used to terminate the switch-case statement. If break is not used, all the cases after the matching case are also executed. For example,

In the above example, expression matches with case 2 . Here, we haven't used the break statement after each case.

Hence, all the cases after case 2 are also executed.

This is why the break statement is needed to terminate the switch-case statement after the matching case. To learn more, visit Java break Statement .

default Case in Java switch-case

The switch statement also includes an optional default case . It is executed when the expression doesn't match any of the cases. For example,

In the above example, we have created a switch-case statement. Here, the value of expression doesn't match with any of the cases.

Hence, the code inside the default case is executed.

Note : The Java switch statement only works with:

  • Primitive data types : byte, short, char, and int
  • Enumerated types
  • String Class
  • Wrapper Classes : Character, Byte, Short, and Integer.
  • Implementation of switch...case on Strings

Table of Contents

  • Java Switch Statement
  • Example: switch statement
  • Flowchart of switch...case
  • break statement
  • default case

Sorry about that.

Related Tutorials

Java Tutorial

Java Switch Statement – How to Use a Switch Case in Java

Ihechikara Vincent Abba

You use the switch statement in Java to execute a particular code block when a certain condition is met.

Here's what the syntax looks like:

Above, the expression in the switch parenthesis is compared to each case . When the expression is the same as the case , the corresponding code block in the case gets executed.

If all the cases do not match the expression , then the code block defined under the default keyword gets executed.

We use the break keyword to terminate the code whenever a certain condition is met (when the expression matches with a case ).

Let's see some code examples.

How to Use a Switch Case in Java

Take a look at the following code:

In the code above, June is printed out. Don't worry about the bulky code. Here's a breakdown to help you understand:

We created an integer called month and assigned a value of 6 to it: int month = 6; .

Next, we created a switch statement and passed in the month variable as a parameter: switch (month){...} .

The value of month , which is acting as the expression for the switch statement, will be compared with every case value in the code. We have case 1 to 12.

The value of month is 6 so it matches with case 6. This is why the code in case 6 was executed. Every other code block got ignored.

Here's another example to simplify things:

In the example above, we created a string called username which has a value of "John".

In the switch statement, username is passed in as the expression. We then created three cases – "Doe", "John", and "Jane".

Out of the three classes, only one matches the value of username — "John". As a result, the code block in case "John" got executed.

How to Use the Default Keyword in a Switch Statement

In the examples in the previous section, our code got executed because one case matched an expression .

In this section, you'll see how to use the default keyword. You can use it as a fallback in situations where none of the cases match the expression .

Here's an example:

The username variable in the example above has a value of  "Ihechikara".

The code block for the default keyword will be executed because none of the cases created match the value of username .

In this article, we saw how to use the switch statement in Java.

We also talked about the switch statement's expression, cases, and default keyword in Java along with their use cases with code examples.

Happy coding!

ihechikara.com

If you read this far, thank the author to show them you care. Say Thanks

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

Javatpoint Logo

Java Tutorial

Control statements, java object class, java inheritance, java polymorphism, java abstraction, java encapsulation, java oops misc.

JavaTpoint

  • Send your Feedback to [email protected]

Help Others, Please Share

facebook

Learn Latest Tutorials

Splunk tutorial

Transact-SQL

Tumblr tutorial

Reinforcement Learning

R Programming tutorial

R Programming

RxJS tutorial

React Native

Python Design Patterns

Python Design Patterns

Python Pillow tutorial

Python Pillow

Python Turtle tutorial

Python Turtle

Keras tutorial

Preparation

Aptitude

Verbal Ability

Interview Questions

Interview Questions

Company Interview Questions

Company Questions

Trending Technologies

Artificial Intelligence

Artificial Intelligence

AWS Tutorial

Cloud Computing

Hadoop tutorial

Data Science

Angular 7 Tutorial

Machine Learning

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures

DAA tutorial

Operating System

Computer Network tutorial

Computer Network

Compiler Design tutorial

Compiler Design

Computer Organization and Architecture

Computer Organization

Discrete Mathematics Tutorial

Discrete Mathematics

Ethical Hacking

Ethical Hacking

Computer Graphics Tutorial

Computer Graphics

Software Engineering

Software Engineering

html tutorial

Web Technology

Cyber Security tutorial

Cyber Security

Automata Tutorial

C Programming

C++ tutorial

Control System

Data Mining Tutorial

Data Mining

Data Warehouse Tutorial

Data Warehouse

RSS Feed

Java switch case with examples

This article helps you understand and use the switch case construct in Java with code examples.

The switch-case construct is a flow control structure that tests value of a variable against a list of values. Syntax of this structure is as follows:

Some Rules about switch-case construct:

  •       Primitive numbers: byte , short , char and int
  •       Primitive wrappers: Byte , Short , Character and Integer .
  •       Enumerated types (enum type).
  •       String literals (since Java 1.7)
  •           The constant_1 , constant_2 , constant_3 , …, constant_n must be a constant or literals of the allowed types.
  •            Each case is tested from top to bottom, until a case is matched and a break   statement is found.
  •            If a case matches the expression , the statements block after the case clause are executed, until a break statement is reached.

           It is not required that each case must have a corresponding break statement. If a matching case block does not have a break statement, the execution will fall through the next case block, until a first break statement is reached or end of switch statement is encountered.

           The statements block after default will be executed if there is no matching case found.

Some Java switch-case examples:

          The following example shows a switch statement that tests for an integer variable. It products the output: The number is Three

          The following example shows a switch statement that tests for an enum type, Priority . It will output the result: Task priority: 3

Related Topics:

  • Using Strings in switch-case statement
  • Notes about execution control statements in Java

Other Recommended Tutorials:

  • 9 Rules about Constructors in Java
  • 12 Rules and Examples About Inheritance in Java
  • 12 Rules of Overriding in Java You Should Know
  • 10 Java Core Best Practices Every Java Programmer Should Know
  • Understand Interfaces in Java
  • Understand abstraction in Java
  • Understand encapsulation in Java
  • Understand inheritance in Java
  • Understand polymorphism in Java

About the Author:

java switch case assignment

Add comment

   

Notify me of follow-up comments

Comments  

Code With C

The Way to Programming

  • C Tutorials
  • Java Tutorials
  • Python Tutorials
  • PHP Tutorials
  • Java Projects

Implementing Switch and Case in Java: Syntax and Use Cases

CodeLikeAGirl

Hey there, lovely readers! Today, we are going to embark on a thrilling Java journey exploring the wondrous world of switch and case statements. 🚀 Are you ready to unravel the mysteries behind their syntax and delve into some snazzy use cases? Let’s roll up our sleeves and dive right in!

Syntax of Switch and Case in Java

Switch statement syntax.

Let’s kick things off by unraveling the syntax behind the mighty switch statement in Java . Buckle up, folks, we’re about to get technical! 🤓

Decision Making with Switch

The switch statement in Java provides a structured way to make decisions based on the value of an expression. It’s like a choose-your-own-adventure book but in the coding realm! 💻

Case Statement Syntax

Now, let’s shine a light on the case statement within the switch block. Get ready to witness some digital magic! 🔮

Using Multiple Cases

Want to spice things up with multiple case statements? Fear not, Java has got your back! Simply stack those cases like a master Jenga player. 🧱

Implementing Switch and Case in Java

Basic implementation.

Time to get our hands dirty with some practical implementation of switch and case statements in Java. Let’s start with the basics, shall we?

Handling Default Case

Ah, the elusive default case! It’s like the safety net that catches you when all else fails. Let’s ensure we’ve got that covered in our Java adventures. 🕵️‍♀️

Advanced Use Cases

Ready to level up your Java game? Let’s explore some advanced use cases where switch statements shine brighter than a diamond! 💎

Nesting Switch Statements

Who says you can’t nest switch statements like a Russian nesting doll? Let’s push the boundaries of Java coding and explore the mesmerizing world of nested switches. 🎉

And there you have it, folks! We’ve navigated through the syntax intricacies and dived into some captivating use cases of switch and case in Java. I hope this journey has been as exhilarating for you as it has been for me. Thank you for joining me today on this Java escapade! Until next time, happy coding and may your switches always be swift and your cases ever so intriguing! 🌟

Thank you for tuning in, fabulous readers! Remember, when in doubt, just switch it up and let the cases fall where they may! 🌈

Implementing Switch and Case in Java: Syntax and Use Cases

Program Code – Implementing Switch and Case in Java: Syntax and Use Cases

Code Output: The selected month is: April

Code Explanation: The program SwitchCaseDemo is a simple demonstration of how to implement the switch and case statements in Java. The main objective here is to convert an integer representing a month (1-12) into its corresponding month name as a string and then print it out. Here’s a step-by-step explanation of its logic and architecture:

  • Variable Declaration: At the beginning of the main method, an integer variable month is declared and initialized to 4. This represents April. However, this could be any number representing a month.
  • Switch-Case Statement: We then hit the meat of the program. A switch statement is initiated with the month variable. What follows is a series of case statements, each checking for a value from 1 to 12, corresponding to the months January through December. For each case, if the value of month matches the case, the monthString variable is assigned the name of the corresponding month.
  • Break Statements: After each case is the break statement. This tells the program to exit the switch statement once it has found a matching case and executed what’s in it. Without break , the program would continue to check through the subsequent cases, which is unnecessary and not how we traditionally use switch-case .
  • Default Case: It’s good practice to include a default case in a switch statement. This handles any values that do not match any of the specified cases. Here, if month doesn’t match any case from 1 to 12, it falls into the default case setting monthString to ‘Invalid month’.
  • Printing Output: Finally, the program prints out ‘The selected month is: ‘ followed by the value of monthString , which should in this case be ‘April’.

The switch-case statement is a neat tool in Java for handling a specific set of values (like the months in a year) cleanly and readably, without having to clutter your code with multiple if-else conditions . It gives a straightforward way to select one of many code paths to execute.

Frequently Asked Questions (FAQ) on Implementing Switch and Case in Java

What is the purpose of using switch and case statements in java.

Switch and case statements in Java are used to make decisions based on the value of a variable. They provide a way to streamline multiple if-else statements, making the code more readable and efficient .

How do you use the switch statement in Java?

In Java, the switch statement is followed by a variable or an expression in parentheses. Each case inside the switch block compares the value of the variable against a constant value. When a match is found, the corresponding block of code is executed.

Can we use strings in a switch statement in Java?

Yes, starting from Java SE 7, you can use strings in a switch statement. This allows you to switch based on string values, providing a more flexible way to make decisions in your code.

What happens if a break statement is omitted in a case in Java?

If a break statement is omitted in a case in Java, the execution will “fall through” to the next case. This means that the code will continue to execute the next case’s statements, regardless of whether the case matches the variable value or not.

Are switch statements more efficient than if-else statements in Java?

Switch statements can be more efficient than long chains of if-else statements because they use “jump” table for decision-making, which can lead to faster execution in some scenarios. However, the actual performance impact may vary based on the specific use case and implementation.

What are some common use cases for switch and case statements in Java?

Switch and case statements are commonly used in scenarios where you have a variable with multiple possible values and you need to perform different actions based on each value. Examples include menu selection, day of the week determination, and state transitions in a state machine .

Can we have nested switch statements in Java?

Yes, you can have nested switch statements in Java . This means placing a switch statement inside another switch statement’s case block. However, nesting switch statements can make the code complex and harder to read, so it’s essential to use this feature judiciously.

Is there any limit to the number of cases in a switch statement in Java?

In Java, there is no specific limit to the number of cases in a switch statement. However, it’s essential to consider the code’s readability and maintainability when deciding how many cases to include in a switch statement.

How does the default case work in a switch statement in Java?

The default case in a switch statement in Java is optional and acts as a catch-all case when none of the other cases match the variable value. If no match is found in any of the cases, the default case block is executed.

Are switch statements considered good practice in Java programming?

Switch statements can be useful for enhancing code readability and maintainability in certain situations. However, overusing switch statements or nesting them too deeply can make the code harder to understand . It’s essential to weigh the pros and cons and use switch statements judiciously in your Java code.

I hope these FAQs help clarify any doubts you may have about implementing switch and case statements in Java ! Feel free to delve into more details or share your experiences 🚀.

You Might Also Like

For loops in java: a developer’s guide to iteration, looping for java: crafting repetitive control structures, control flow in java: understanding loops, for looping in java: syntax and best use cases, java to map: converting collections and data structures.

Avatar photo

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Latest Posts

79 Ultimate Guide to Hybrid Network Mobility Support Project in Named Data Networking

Ultimate Guide to Hybrid Network Mobility Support Project in Named Data Networking

68 Enhanced Security Network Coding System Project for Two-Way Relay Networks

Enhanced Security Network Coding System Project for Two-Way Relay Networks

88 Cutting-Edge Network Security Project: Distributed Event-Triggered Trust Management for Wireless Sensor Networks

Cutting-Edge Network Security Project: Distributed Event-Triggered Trust Management for Wireless Sensor Networks

72 Wireless Ad Hoc Network Routing Protocols Under Security Attack Project

Wireless Ad Hoc Network Routing Protocols Under Security Attack Project

codewithc 61 1 Cutting-Edge Collaborative Network Security Project for Multi-Tenant Data Centers in Cloud Computing

Cutting-Edge Collaborative Network Security Project for Multi-Tenant Data Centers in Cloud Computing

Privacy overview.

Sign in to your account

Username or Email Address

Remember Me

Java 14: Switch Expressions Enhancements Examples

1. what’s new for switch block in java 14, 2. new form of switch label, 3. switch expressions examples.

Related Topics:

  • Using Strings in switch-case statement
  • Notes about execution control statements in Java

Other Recommended Tutorials:

  • 9 Rules about Constructors in Java
  • 12 Rules and Examples About Inheritance in Java
  • 12 Rules of Overriding in Java You Should Know
  • 10 Java Core Best Practices Every Java Programmer Should Know
  • Understand Interfaces in Java
  • Understand abstraction in Java
  • Understand encapsulation in Java
  • Understand inheritance in Java
  • Understand polymorphism in Java

About the Author:

java switch case assignment

Add comment

   

Notify me of follow-up comments

Comments  

java switch case assignment

Modern Java Switch Expressions

java switch case assignment

In this blog, I will cover some improvements of switch. The old syntax dates back to the early day of Java, and its handling is a bit cumbersome.

Let's look at the newer, slightly modified syntax for switch, called Switch Expressions. With it, case distinctions can be formulated much more elegantly than before.

Introductory example

To demonstrate switch expressions, I resort to mapping days of the week to their textual length as an example.

To better understand the need for this syntax improvement, let’s first examine how this task would have been formulated with the old syntax. Afterwards, we’ll look at the advantages provided by the new syntax of switch.

Analysis: What were some weaknesses of the switch so far?

Let’s start with the implementation of mapping weekdays of type DayOfWeek to their textual length using the older syntax:

Modern Switch Expressions

Let's have a critical look at the source code. First of all, the shown construct does not appear elegant and is also quite long. The multiple specifications of values need accustoming, too. Even worse, a break is needed so that the processing runs without surprise and there is no fall-through. Moreover, we need to set the (artificial) auxiliary variable numOfLetters correctly in each branch. In particular, despite the actually complete coverage of the enum values, the default is necessary. Otherwise, the compiler complains that the variable numOfLetters may not be initialized – unless you have already assigned a value to it initially. So how is it better?

Syntax of the new Switch Expressions

With the new "Switch Expressions", expressing case distinctions is made much easier and provides an intuitive notation:

From this example, we notice some syntactic innovations: In addition to the obvious arrow instead of the colon, multiple values can now be specified after the case. Conveniently, there is no more need for break: The statements after the arrow are only executed specifically for the case and no fall-through exists with this syntax. Besides, the switch can now return a value, which avoids the need to define auxiliary variables. Instead of just stating a value after the arrow, it is also possible to specify expressions such as assignments or method calls without any problems. And even better, of course, still without the need for a break. Furthermore, this is no longer allowed in the new syntax after the arrow. 

Special feature: completeness check 

In the old version of switch it was possible to omit the default or to specify a case for individual values, for example WEDNESDAY. The compiler wouldn't have recognized this in switch itself. This would only have been pointed out later when accessing the variable used in the example that it is not initialized in every case. 

The handling has conveniently improved with the new switch expressions: Let’s assume we did not specify WEDNESDAY in the above example. Then this is directly criticized by the compiler: "A switch expression should cover all possible values." Additionally, IDEs offer the choice of adding either the appropriate case or a default, but not both: full coverage of the enum values is automatically detected. This innovation is necessary because the switch must now return a value in each case.

While it is still quite clear for enums with a limited set of possible values, the following question arises: How does it work for other types, such as ints? In such cases, the compiler can only state that possibly not all values are covered, and complains: "A switch expression should cover all possible values." Then the IDEs suggest to add a default – here indicated by the line commented out:

Other reasons for the innovation

Let me go into more detail about the completeness check of the value coverage in the cases because there are sometimes difficulties when using switch. 

Pitfall 1: Incomplete value specifications

With the Date and Time API, of course, the complicated construct could be simplified significantly: month.getDisplayName(TextStyle.FULL, Locale.UK).

‍ In the following, we want to map a value from the enumeration java.time.Month to the corresponding month name. Conventionally, this can be solved somewhat as follows:

Again, the shown construct is not really elegant. Depending on whether a case is de fined for the value Month.JULY or not, one gets the value "July" or "N/A". Also, a break is needed to ensure that the processing is performed without surprise. 

Pitfall 2: Fall-through and default between the breaks

‍ Let’s consider something rather clumsy, namely the default in the middle of the cases and without a break:

The input Month.FEBRUARY results in the value "February" as expected, but surprisingly this also happens for the input Month.JULY. Why is this? First, because of the cases unlisted value JULY, the default branch is executed. Because of the missing break, a fall-through is also (unexpectedly) triggered. This causes the code for case FEBRUARY to be executed, which can be quite confusing. 

Remedy with the new switch expressions

‍ With the help of the new syntax, the whole thing is much easier to write as follows: 

It is especially worth mentioning that one can directly return the value calculated by the switch construct. Furthermore, the fall-through does not occur. Thus the input Month.FEBRUARY returns "February" as expected, and moreover the default in the middle of the cases is not quite as dramatic, though certainly not pretty either. Unlike the old syntax, the input Month.JULY just no longer results in an unexpected output "February", but as specified by default in "N/A". Furthermore, if there were a case JULY, it would always be executed, regardless of the position of the default, thus analogous to the behavior of the previous switch statement.

Conclusion 

The Java releases up to and including 13 are rather manageable in terms of their innovations. This is true even for Java 11 as an LTS version. Fortunately, Java 14 brings a good slew of useful enhancements: On the one hand, there are the convenient syntax changes in switch. Another is the multi-line strings, called Text Blocks. These are covered in one of the next blogs. 

Let me conclude: The new syntax of switch seems to be just a small change, but it has an enormous effect on readability and ease of use. This blog introduced the benefits and simplifications of the new syntax of switch so that you can profit from it in your own projects.

Find me a job!

What’s a Rich Text element?

The rich text element allows you to create and format headings, paragraphs, blockquotes, images, and video all in one place instead of having to add and format them individually. Just double-click and easily create content.

Static and dynamic content editing

A rich text element can be used with static or dynamic content. For static content, just drop it into any page and begin editing. For dynamic content, add a rich text field to any collection and then connect a rich text element to that field in the settings panel. Voila!

How to customize formatting for each rich text

Headings, paragraphs, blockquotes, figures, images, and figure captions can all be styled after a class is added to the rich text element using the "When inside of" nested selector system.

java switch case assignment

Holen Sie sich Ihren kostenlosen Leitfaden zum erfolgreichen Employer Branding!

Continue reading, visual studio code shortcuts for cleaning up your code, visual studio code shortcuts for navigating your code, cross platform mobile development frameworks to use in 2024, subscribe to devdigest.

Get a weekly, curated and easy to digest email with everything that matters in the developer world.

From developers. For developers.

Introduction to Java

  • What Is Java? A Beginner's Guide to Java and Its Evolution
  • Why Java is a Popular Programming Language?
  • Top 10 Reasons Why You Should Learn Java
  • Why Java is a Secure language?
  • What are the different Applications of Java?
  • Java for Android: Know the importance of Java in Android
  • What is the basic Structure of a Java Program?
  • What is the difference between C, C++ and Java?
  • Java 9 Features and Improvements
  • Top 10 Java Frameworks You Should Know
  • Netbeans Tutorial: What is NetBeans IDE and how to get started?

Environment Setup

  • How To Set Path in Java?
  • How to Write Hello World Program in Java?
  • How to Compile and Run your first Java Program?
  • Learn How To Use Java Command Line Arguments With Examples

Control Statements

  • What is for loop in java and how to implement it?
  • What is a While Loop in Java and how to use it?
  • What is for-each loop in Java?
  • What is a Do while loop in Java and how to use it?

What is a Switch Case In Java?

Java core concepts.

  • Java Tutorial For Beginners – Java Programming Made Easy!
  • What are the components of Java Architecture?
  • What are Comments in Java? – Know its Types
  • What are Java Keywords and reserved words?
  • What is a Constructor in Java?
  • What is the use of Destructor in Java?
  • Know About Parameterized Constructor In Java With Examples
  • What are Operators in Java and its Types?
  • What Are Methods In Java? Know Java Methods From Scratch
  • What is Conditional Operator in Java and how to write it?
  • What is a Constant in Java and how to declare it?
  • What is JIT in Java? – Understanding Java Fundamentals
  • What You Should Know About Java Virtual Machine?
  • What is the role for a ClassLoader in Java?
  • What is an Interpreter in Java?
  • What is Bytecode in Java and how it works?
  • What is a Scanner Class in Java?
  • What is the Default Value of Char in Java?
  • this Keyword In Java – All You Need To Know
  • What is Protected in Java and How to Implement it?
  • What is a Static Keyword in Java?
  • What is an Array Class in Java and How to Implement it?
  • What is Ternary Operator in Java and how can you use it?
  • What is Modulus in Java and how does it work?
  • What is the difference between Method Overloading And Overriding?
  • Instance variable In Java: All you need to know

Know All About the Various Data Types in Java

What is typecasting in java and how does it work.

  • How to Create a File in Java? – File Handling Concepts
  • File Handling in Java – How To Work With Java Files?
  • What is a Comparator Interface in Java?
  • Comparable in Java: All you need to know about Comparable & Comparator interfaces
  • What is Iterator in Java and How to use it?
  • Java Exception Handling – A Complete Reference to Java Exceptions
  • All You Need to Know About Final, Finally and Finalize in Java
  • How To Implement Volatile Keyword in Java?
  • Garbage Collection in Java: All you need to know
  • What is Math Class in Java and How to use it?
  • What is a Java Thread Pool and why is it used?
  • Synchronization in Java: What, How and Why?
  • Top Data Structures & Algorithms in Java That You Need to Know
  • Java EnumSet: How to use EnumSet in Java?
  • How to Generate Random Numbers using Random Class in Java?
  • Generics in Java – A Beginners Guide to Generics Fundamentals
  • What is Enumeration in Java? A Beginners Guide
  • Transient in Java : What, Why & How it works?
  • What is Wait and Notify in Java?
  • Swing In Java : Know How To Create GUI With Examples
  • Java AWT Tutorial – One Stop Solution for Beginners
  • Java Applet Tutorial – Know How to Create Applets in Java
  • How To Implement Static Block In Java?
  • What is Power function in Java? – Know its uses
  • Java Array Tutorial – Single & Multi Dimensional Arrays In Java
  • Access Modifiers in Java: All you need to know
  • What is Aggregation in Java and why do you need it?
  • How to Convert Int to String in Java?
  • What Is A Virtual Function In Java?
  • Java Regex – What are Regular Expressions and How to Use it?
  • What is PrintWriter in Java and how does it work?
  • All You Need To Know About Wrapper Class In Java : Autoboxing And Unboxing
  • How to get Date and Time in Java?
  • What is Trim method in Java and How to Implement it?
  • How do you exit a function in Java?
  • What is AutoBoxing and unboxing in Java?
  • What is Factory Method in Java and how to use it?
  • Threads in Java: Know Creating Threads and Multithreading in Java
  • Join method in Java: How to join threads?
  • What is EJB in Java and How to Implement it?
  • What is Dictionary in Java and How to Create it?
  • Daemon Thread in Java: Know what are it's methods
  • How To Implement Inner Class In Java?
  • What is Stack Class in Java and how to use it?

Java Strings

  • What is the concept of String Pool in java?
  • Java String – String Functions In Java With Examples
  • Substring in Java: Learn how to use substring() Method
  • What are Immutable String in Java and how to use them?
  • What is the difference between Mutable and Immutable In Java?
  • BufferedReader in Java : How To Read Text From Input Stream
  • What are the differences between String, StringBuffer and StringBuilder?
  • Split Method in Java: How to Split a String in Java?
  • Know How to Reverse A String In Java – A Beginners Guide
  • What is Coupling in Java and its different types?
  • Everything You Need to Know About Loose Coupling in Java

Objects and Classes

  • Packages in Java: How to Create and Use Packages in Java?
  • Java Objects and Classes – Learn how to Create & Implement
  • What is Object in Java and How to use it?
  • Singleton Class in Java – How to Use Singleton Class?
  • What are the different types of Classes in Java?
  • What is a Robot Class in Java?
  • What is Integer class in java and how it works?
  • What is System Class in Java and how to implement it?
  • Char in Java: What is Character class in Java?
  • What is the Boolean Class in Java and how to use it?
  • Object Oriented Programming – Java OOPs Concepts With Examples
  • Inheritance in Java – Mastering OOP Concepts
  • Polymorphism in Java – How To Get Started With OOPs?
  • How To Implement Multiple Inheritance In Java?
  • Java Abstraction- Mastering OOP with Abstraction in Java
  • Encapsulation in Java – How to master OOPs with Encapsulation?
  • How to Implement Nested Class in Java?
  • What is the Use of Abstract Method in Java?
  • What is Association in Java and why do you need it?
  • What is the difference between Abstract Class and Interface in Java?
  • What is Runnable Interface in Java and how to implement it?
  • What is Cloning in Java and its Types?
  • What is Semaphore in Java and its use?
  • What is Dynamic Binding In Java And How To Use It?

Java Collections

  • Java Collections – Interface, List, Queue, Sets in Java With Examples
  • List in Java: One Stop Solution for Beginners
  • Java ArrayList: A Complete Guide for Beginners
  • Linked List in Java: How to Implement a Linked List in Java?
  • What are Vector in Java and how do we use it?
  • What is BlockingQueue in Java and how to implement it?
  • How To Implement Priority Queue In Java?
  • What is Deque in Java and how to implement its interface?
  • What are the Legacy Classes in Java?
  • Java HashMap – Know How to Implement HashMap in Java
  • What is LinkedHashSet in Java? Understand with examples
  • How to Implement Map Interface in Java?
  • Trees in Java: How to Implement a Binary Tree?
  • What is the Difference Between Extends and Implements in Java?
  • How to Implement Shallow Copy and Deep Copy in Java
  • How to Iterate Maps in Java?
  • What is an append Method in Java?
  • How To Implement Treeset In Java?
  • Java HashMap vs Hashtable: What is the difference?
  • How to Implement Method Hiding in Java
  • How To Best Implement Concurrent Hash Map in Java?
  • How To Implement Marker Interface In Java?

Java Programs

  • Palindrome in Java: How to check a number is palindrome?
  • How to check if a given number is an Armstrong number or not?
  • How to Find the largest number in an Array in Java?
  • How to find the Sum of Digits in Java?
  • How To Convert String To Date In Java?
  • Ways For Swapping Two Numbers In Java
  • How To Implement Addition Of Two Numbers In Java?
  • How to implement Java program to check Leap Year?
  • How to Calculate Square and Square Root in Java?
  • How to implement Bubble Sort in Java?
  • How to implement Perfect Number in Java?
  • What is Binary Search in Java? How to Implement it?
  • How to Perform Merge Sort in Java?

Top 30 Patterns in Java: How to Print Star, Number and Character

  • Know all about the Prime Number program in Java

How To Display Fibonacci Series In Java?

  • How to Sort Array, ArrayList, String, List, Map and Set in Java?
  • How To Create Library Management System Project in Java?

How To Practice String Concatenation In Java?

  • How To Convert Binary To Decimal In Java?
  • How To Convert Double To Int in Java?
  • How to convert Char to Int in Java?
  • How To Convert Char To String In Java?

How to Create JFrame in Java?

  • What is Externalization in Java and when to use it?
  • How to read and parse XML file in Java?
  • How To Implement Matrix Multiplication In Java?
  • How To Deal With Random Number and String Generator in Java?
  • Java Programs for Practice: Know the Simple Java Programs for Beginners

Advance Java

  • How To Connect To A Database in Java? – JDBC Tutorial
  • Advanced Java Tutorial- A Complete Guide for Advanced Java
  • Servlet and JSP Tutorial- How to Build Web Applications in Java?
  • Introduction to Java Servlets – Servlets in a Nutshell
  • What Is JSP In Java? Know All About Java Web Applications
  • How to Implement MVC Architecture in Java?
  • What is JavaBeans? Introduction to JavaBeans Concepts
  • Know what are the types of Java Web Services?
  • JavaFX Tutorial: How to create an application?
  • What is Executor Framework in Java and how to use it?
  • What is Remote Method Invocation in Java?
  • Everything You Need To Know About Session In Java?
  • Java Networking: What is Networking in Java?
  • What is logger in Java and why do you use it?
  • How To Handle Deadlock In Java?
  • Know all about Socket Programming in Java
  • Important Java Design Patterns You Need to Know About
  • What is ExecutorService in Java and how to create it?
  • Struts 2 Tutorial – One Stop Solution for Beginners
  • What is Hibernate in Java and Why do we need it?
  • What is Maven in Java and how do you use it?
  • What is Machine Learning in Java and how to implement it?

Career Opportunities

  • Java Developer Resume: How to Build an Impressive Resume?
  • What is the Average Java Developer Salary?

Interview Questions

  • Java Interview Questions and Answers
  • Top MVC Interview Questions and Answers You Need to Know in 2024
  • Top 50 Java Collections Interview Questions You Need to Know in 2024
  • Top 50 JSP Interview Questions You Need to Know in 2024
  • Top 50 Hibernate Interview Questions That Are A Must in 2024

Programming & Frameworks

Java programming language has conditional and control statements which optimizes the logic while writing a program. Hustle free logic building using the switch case results in improved efficiency. Using a switch case in java optimizes the readability of the code while working on multiple test expressions. In this article, you will learn about switch case in java with various examples. Following are the topics discussed in this article:

Rules To Remember

Break statement in switch case, nested switch case.

  • Fall-Through Switch Case

Enum In Switch Case

String in switch case, what is a switch case in java.

Java switch statement is like a conditional statement which tests multiple values and gives one output. These multiple values that are tested are called cases. It is like a multi-branch statement. After the release of java 7 we can even use strings in the cases. Following is the syntax of using a switch case in Java .

There are a certain rules one must keep in mind while declaring a switch case in java. Following are a certain points to remember while writing a switch case in java.

We cannot declare duplicate values in a switch case.

The values in the case and the data type of the variable in a switch case must be same.

Variables are not allowed in a case, it must be a constant or a literal.

The break statement fulfills the purpose of terminating the sequence during execution.

It is not necessary to include the break statement, the execution will move to the next statement if the break statement is missing.

The default statement is optional as well, it can appear anywhere in the block.

Break statement is used to control the flow of the execution, as soon as the expression is satisfied the execution moves out the switch case block.

Output: july

Nested switch case incorporates another switch case in an existing switch case. Following is an example showing a nested switch case.

Output: advance java

Fall Through Switch Case

Whenever there is no break statement involved in a switch case block. All the statements are executed even if the test expression is satisfied. Following is an example of a fall through switch case.

Switch case allows enum as well. Enum is basically a list of named constants. Following is an example of the use of enum in a switch case.

After the release of Java 7, a switch case can have strings as a case. Following is an example of using string as cases in a switch statement.

In this article, we have discussed how we can use switch case in java with various examples. With the use of conditional statements it becomes easier to test multiple conditions at once and also generate an optimized solution of rather difficult problem. Java programming language is abundant in such concepts which makes a developer’s life easier and hustle free. Kick-start your learning and master all the skills required to become a java developer. Enroll to Edureka’s Java Certification program and unleash your potential into making top notch applications.

Got a question for us? please mention this in the comments section of this ‘Switch Case In Java’ article and we will get back to you as soon as possible.

Recommended videos for you

Mastering regex in perl, microsoft sharepoint 2013 : the ultimate enterprise collaboration platform, hibernate-the ultimate orm framework, effective persistence using orm with hibernate, building web application using spring framework, rapid development with cakephp, node js express: steps to create restful web app, node js : steps to create restful web app, microsoft sharepoint 2013 : the ultimate enterprise collaboration platform, learn perl-the jewel of scripting languages, microsoft .net framework : an intellisense way of web development, portal development and text searching with hibernate, ms .net – an intellisense way of web development, introduction to java/j2ee & soa, service-oriented architecture with java, responsive web app using cakephp, spring framework : introduction to spring web mvc & spring with bigdata, microsoft sharepoint-the ultimate enterprise collaboration platform, create restful web application with node.js express, a day in the life of a node.js developer, recommended blogs for you, how to work with dynamic memory allocation c++, what is ternary operator in php and how is it used, how to build a javascript calculator, java collections – interface, list, queue, sets in java with examples, how to implement print_r in php, java exceptions cheat sheet – level up your java knowledge, python frameworks: what are the top 5 frameworks in python, how to get current date and time in java, what is json know how it works with examples, express.js tutorial – one stop solution for beginners, what is nextchar in java and how to implement it, everything you need to know about variables in java, what is the continue statement in java, top 50 php interview questions you must prepare in 2024, join the discussion cancel reply, trending courses in programming & frameworks, full stack web development internship program.

  • 29k Enrolled Learners
  • Weekend/Weekday

Java Certification Training Course

  • 75k Enrolled Learners

Python Scripting Certification Training

  • 14k Enrolled Learners

Flutter Application Development Course

  • 12k Enrolled Learners

Spring Framework Certification Course

Node.js certification training course.

  • 10k Enrolled Learners

Advanced Java Certification Training

  • 7k Enrolled Learners

Data Structures and Algorithms using Java Int ...

  • 31k Enrolled Learners

Microsoft .NET Framework Certification Traini ...

  • 6k Enrolled Learners

PHP & MySQL with MVC Frameworks Certifica ...

  • 5k Enrolled Learners

Browse Categories

Subscribe to our newsletter, and get personalized recommendations..

Already have an account? Sign in .

20,00,000 learners love us! Get personalised resources in your inbox.

At least 1 upper-case and 1 lower-case letter

Minimum 8 characters and Maximum 50 characters

We have recieved your contact details.

You will recieve an email from us shortly.

  • Java Language Updates
  • Pattern Matching

Pattern Matching for switch Expressions and Statements

A switch statement transfers control to one of several statements or expressions, depending on the value of its selector expression. In earlier releases, the selector expression must evaluate to a number, string or enum constant, and case labels must be constants. However, in this release, the selector expression can be any reference type or an int type but not a long , float , double , or boolean type, and case labels can have patterns. Consequently, a switch statement or expression can test whether its selector expression matches a pattern, which offers more flexibility and expressiveness compared to testing whether its selector expression is exactly equal to a constant.

For background information about pattern matching for switch expressions and statements, see JEP 441 .

Consider the following code that calculates the perimeter of certain shapes from the section Pattern Matching for the instanceof Operator :

You can rewrite this code to use a pattern switch expression as follows:

The following example uses a switch statement instead of a switch expression:

Selector Expression Type

When clauses, qualified enum constants as case constants, pattern label dominance, type coverage in switch expressions and statements, inference of type arguments in record patterns, scope of pattern variable declarations, null case labels.

You can add a Boolean expression right after a pattern label with a when clause. This is called a guarded pattern label . The Boolean expression in the when clause is called a guard . A value matches a guarded pattern label if it matches the pattern and, if so, the guard also evaluates to true. Consider the following example:

You can move the Boolean expression s.length == 1 right after the the case label with a when clause:

The first pattern label (which is a guarded pattern label) matches if obj is both a String and of length 1. The second patten label matches if obj is a String of a different length.

A guarded patten label has the form p when e where p is a pattern and e is a Boolean expression. The scope of any pattern variable declared in p includes e .

You can use qualified enum constants as case constants in switch expressions and statements.

Consider the following switch expression whose selector expression is an enum type:

In the following example, the type of the selector expression is an interface that's been implemented by two enum types. Because the type of the selector expression isn't an enum type, this switch expression uses guarded patterns instead:

However, switch expressions and statements allow qualified enum constants, so you could rewrite this example as follows:

Therefore, you can use an enum constant when the type of the selector expression is not an enum type provided that the enum constant's name is qualified and its value is assignment-compatible with the type of the selector expression.

The first pattern label case CharSequence cs dominates the second pattern label case String s because every value that matches the pattern String s also matches the pattern CharSequence cs but not the other way around. It's because String is a subtype of CharSequence .

A pattern label can dominate a constant label. These examples cause compile-time errors:

Although the value 1 matches both the guarded pattern label case Integer i when i > 0 and the constant label case 1 , the guarded pattern label doesn't dominate the constant label. Guarded patterns aren't checked for dominance because they're generally undecidable. Consequently, you should order your case labels so that constant labels appear first, followed by guarded pattern labels, and then followed by nonguarded pattern labels:

As described in Switch Expressions , the switch blocks of switch expressions and switch statements, which use pattern or null labels, must be exhaustive. This means that for all possible values, there must be a matching switch label. The following switch expression is not exhaustive and generates a compile-time error. Its type coverage consists of the subtypes of String or Integer , which doesn't include the type of the selector expression, Object :

However, the type coverage of the case label default is all types, so the following example compiles:

The compiler takes into account whether the type of a selector expression is a sealed class. The following switch expression compiles. It doesn't need a default case label because its type coverage is the classes A , B , and C , which are the only permitted subclasses of S , the type of the selector expression:

The compiler can also determine the type coverage of a switch expression or statement if the type of its selector expression is a generic sealed class. The following example compiles. The only permitted subclasses of interface I are classes A and B . However, because the selector expression is of type I<Integer> , the switch block requires only class B in its type coverage to be exhaustive:

The type of a switch expression or statement's selector expression can also be a generic record. As always, a switch expression or statement must be exhaustive. The following example doesn't compile. No match for a Pair exists that contains two values, both of type A :

The following example compiles. Interface I is sealed. Types C and D cover all possible instances:

If a switch expression or statement is exhaustive at compile time but not at run time, then a MatchException is thrown. This can happen when a class that contains an exhaustive switch expression or statement has been compiled, but a sealed hierarchy that is used in the analysis of the switch expression or statement has been subsequently changed and recompiled. Such changes are migration incompatible and may lead to a MatchException being thrown when running the switch statement or expression. Consequently, you need to recompile the class containing the switch expression or statement.

Consider the following two classes ME and Seal :

The switch expression in the class ME is exhaustive and this example compiles. When you run ME , it prints the value 1 . However, suppose you edit Seal as follows and compile this class and not ME :

When you run ME , it throws a MatchException :

The compiler can infer the type arguments for a generic record pattern in all constructs that accept patterns: switch statements, instanceof expressions, and enhanced for statements.

In the following example, the compiler infers MyPair(var s, var i) as MyPair<String, Integer>(String s, Integer i) :

See Record Patterns for more examples of inference of type arguments in record patterns.

As described in the section Pattern Matching for the instanceof Operator , the scope of a pattern variable is the places where the program can reach only if the instanceof operator is true :

In a switch expression or statement, the scope of a pattern variable declared in a case label includes the following:

The scope of pattern variable c includes the when clause of the case label that contains the declaration of c .

The expression, block, or throw statement that appears to the right of the arrow of the case label:

The scope of pattern variable c includes the block to the right of case Character c -> . The scope of pattern variable i includes the println statement to the right of case Integer i -> .

The switch -labeled statement group of a case label:

The scope of pattern variable c includes the case Character c statement group: the two if statements and the println statement that follows them. The scope doesn't include the default statement group even though the switch statement can execute the case Character c statement group, fall through the default label, and then execute the default statement group.

If this code were allowed, and the value of the selector expression, obj , were a Character , then the switch statement can execute the case Character c statement group and then fall through the case Integer i label, where the pattern variable i would have not been initialized.

This example prints null! when obj is null instead of throwing a NullPointerException .

You may not combine a null case label with anything but a default case label. The following generates a compiler error:

However, the following compiles:

If a selector expression evaluates to null and the switch block does not have null case label, then a NullPointerException is thrown as normal. Consider the following switch statement:

Although the pattern label case Object obj matches objects of type String , this example throws a NullPointerException . The selector expression evaluates to null , and the switch expression doesn't contain a null case label.

Table of Contents

Use of switch case in java, how does the switch statement work, syntax of switch case in java[1] , execution while omitting the break statement, more examples:, conclusion , what is switch case in java and how to use switch statement in java.

Switch Case in Java

The switch statement or switch case in java is a multi-way branch statement. Based on the value of the expression given, different parts of code can be executed quickly. The given expression can be of a primitive data type such as int, char, short, byte, and char. With JDK7, the switch case in java works with the string and wrapper class and enumerated data type ( enum in java ).

The switch case in java is used to select one of many code blocks for execution.

Break keyword: As java reaches a break keyword, the control breaks out of the switch block. The execution of code stops on encountering this keyword, and the case testing inside the block ends as the match is found. A lot of execution time can be saved because it ignores the rest of the code's execution when there is a break.

Default keyword: The keyword is used to specify the code executed when the expression does not match any test case.

Want a Top Software Development Job? Start Here!

Want a Top Software Development Job? Start Here!

This is how switch case in Java work:

The switch case in Java works like an if-else ladder, i.e., multiple conditions can be checked at once. Switch is provided with an expression that can be a constant or literal expression that can be evaluated. The value of the expression is matched with each test case till a match is found. If there is no match, the default keyword, if specified- the associated code executes. Otherwise, the code specified for the matched test case is executed.

There are some things to be remembered while using switch case in java:

  • Two cases cannot have the same value
  • The data type of variable in the switch needs to be the same as all test cases' values.
  • The value for the cases needs to be literal or constant but not a variable. For example:

Valid expressions: switch (1+2+3+4) , switch(1*2+3%4)

Invalid expressions: switch(ef+gh), switch(e+f+g)

  • The break statement is used to terminate the statement sequence inside the switch.
  • The test case values need not be in order (ascending or descending). It can occur as per requirement.
  • If the break statement is omitted, the execution will continue into the next test case.
  • The default statement can appear anywhere inside the switch block, but a break statement should follow it if the default is not in the end.
  • Nesting is allowed, but it makes the program more complex.

For example, the code below uses the monthly number to calculate the month name:

public class Main {

  public static void main(String[] args) {

int month = 4;

    switch (month) {

      case 1:

        System.out.println("January");

        break;

      case 2:

        System.out.println("February");

      case 3:

        System.out.println("March");

      case 4:

        System.out.println("April");

      case 5:

        System.out.println("May");

      case 6:

        System.out.println("June");

     default: System.out.println("In next half");

SwitchStatement.

Learn From The Best Mentors in the Industry!

Learn From The Best Mentors in the Industry!

The syntax of the switch statement is as follows:

switch(expression)

   // The switch block has case statements whose values must be of the same type of expression

   case value1 :

   // Code statement to be executed

   break; // break is optional

   case value2 :

   // There can be several case statements

   // When none of the cases is true, a default statement is used, and no break is needed in the default case.

   default :

Since the break statement is optional, we can omit it. On execution without a break statement, control will continue into the next case. There can be multiple cases without a break statement between them as it is desirable in some cases, such as the given one. This code displays whether a month has 30, 31, or 28 days:

Java program to demonstrate switch case with multiple cases without break statements.

      case 1:   

      case 3:  

      case 7:

      case 8:

      case 10:

      case 12:

        System.out.println("31 days");

     case 2:  System.out.println("28 days");

     case 4:

     case 6:

     case 9:

     case 11:

     System.out.println("30 days");

     default: System.out.println("Error");

OmittingtheBreakStatement

Nested Switch Case in Java

A switch case can be used as a part of an outer switch's statement sequence. This is known as a nested switch case in java. As a switch case defines its block, the case constraints in the inner switch do not conflict with those in the outer switch. Here is a Java program to demonstrate nested switch case statement:

public class Main { 

public static void main(String[] args) 

String Branch = "CS"; 

int year = 1; 

switch (year) { 

System.out.println("elective courses : Advance Maths, Algebra"); 

switch (Branch)  

case "CS": 

case "ECE": 

System.out.println("elective courses : ML, Big Data"); 

case "IT": 

System.out.println("elective courses : Software Engineering"); 

System.out.println("Elective courses : English"); 

NestedSwitchCase

Java Program to Demonstrate the Use of Enum in Switch Statement  

public class Main {      

      public enum Day {  S, M, T, W, Th, F, St  }    

      public static void main(String args[])    

      {    

        Day[] DayNow = Day.values();    

          for (Day Now : DayNow)    

          {    

                switch (Now)    

                {    

                    case S:    

                        System.out.println("Sunday");    

                        break;    

                    case M:    

                        System.out.println("Monday");    

                    case T:    

                        System.out.println("Tuesday");    

                        break;         

                    case W:    

                        System.out.println("Wednesday");    

                    case Th:    

                        System.out.println("Thursday");    

                    case F:    

                        System.out.println("Friday");    

                    case St:    

                        System.out.println("Saturday");    

                }    

            }    

        }    

EnuminSwitchStatement%20

Java Program to Demonstrate the Use of Wrapper class in Switch Statement  

public class Main {       

      public static void main(String args[])  

      {         

            Integer age = 18;        

            switch (age)  

            {  

                case (16):            

                    System.out.println("You are not an adult.");  

                    break;  

                case (18):                

                    System.out.println("You are an adult.");  

                case (65):                

                    System.out.println("You are senior citizen.");  

                default:  

                    System.out.println("Please give the valid age.");  

            }             

        }  

WrapperclassinSwitchState

Don't miss out on the opportunity to become a Certified Professional with Simplilearn's Post Graduate Program in Full Stack Web Development . Enroll Today!

The switch case in java executes one statement from multiple ones. Thus, it is like an if-else-if ladder statement. It works with a lot of data types. The switch statement is used to test the equality of a variable against several values specified in the test cases. 

Java is one of the most widely used programming languages used today. And if you wish to make a career out of it, mastering it is definitely the first step. Check Simplilearn's P ost Graduate Program in Full Stack Web Development . This course can help you gain the right skills and make you job-ready.

If you have any questions, feel free to post them in the comments section below. Our team will get back to you at the earliest.

Our Software Development Courses Duration And Fees

Software Development Course typically range from a few weeks to several months, with fees varying based on program and institution.

Recommended Reads

A Guide on How to Become a Site Reliability Engineer (SRE)

All You Need to Know About C++ Switch

An Introduction to Circuit Switching and Packet Switching

How L&D Professionals Are Using Digital Bootcamps to Build Teams of Tomorrow

What Is Kerberos, How Does It Work, and What Is It Used For?

A Perfect Guide That Explains the Differences Between a Hub and a Switch

Get Affiliated Certifications with Live Class programs

Post graduate program in full stack web development.

  • Live sessions on the latest AI trends, such as generative AI, prompt engineering, explainable AI, and more
  • Caltech CTME Post Graduate Certificate

Full Stack Web Developer - MEAN Stack

  • Comprehensive Blended Learning program
  • 8X higher interaction in live online classes conducted by industry experts

Automation Testing Masters Program

  • Comprehensive blended learning program
  • 200 hours of Applied Learning
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.

Mark O'Neill

Mastering the JavaScript switch Statement

Share this article

Mastering the JavaScript switch Statement

switch Statement Basics: Anatomy and structure

Switch vs. if-else, switch statement functionality and techniques:, common issues and pitfalls, frequently asked questions (faqs) about javascript switch statement.

The JavaScript switch statement is a way to make decisions in your code based on different conditions. It is a more organized and concise alternative to using multiple if-else statements. The switch statement evaluates a given expression, which can be a variable or a value, and compares it to several possible cases. If the value of the expression matches one of the cases, the associated code block (a set of instructions) is executed. If no match is found, an optional default case can be executed as a fallback, meaning it runs when none of the other cases apply.

For example, here’s a simple switch statement that checks the value of a variable called day :

By mastering switch statements, you can write cleaner, more efficient, and better-organized JavaScript code, ultimately improving your overall programming skills.

switch statements begins with the keyword switch , followed by an expression in parentheses. This expression is compared to a series of case labels enclosed in a switch block. Each case label represents a distinct value, and the code block that follows the case is executed when the expression matches the case label’s value. A break statement is typically used to exit the switch block after a matching case is executed, ensuring that only the intended code block runs, and preventing fall-through to the next cases. Optionally, a default case can be included to provide a fallback action when none of the case labels match the expression, ensuring a response for unknown values.

The switch statement is an alternative to using if-else statements when you have multiple conditions to handle. While if-else statements are suitable for checking a series of conditions that can be expressed as true or false, switch statements are more efficient when dealing with a single expression that can take on multiple distinct values. In essence, switch statements can make your code cleaner, more organized, and easier to read when you have several related conditions to manage.

For example, consider the following if-else structure:

The equivalent switch statement would look like this:

The switch statement offers a more organized and readable way to handle multiple conditions, particularly when dealing with a large number of cases. In a switch statement, the expression being evaluated is the variable or value inside the parentheses (in this example, the variable color ).

When to use switch over if-else

  • Large number of single-variable conditions: When you have a large number of conditions to handle, switch statements are generally more organized and easier to read than if-else chains.
  • Single variable evaluation: If the conditions you are evaluating are based on a single variable or expression with multiple distinct values, switch statements can provide a more efficient and cleaner solution than if-else patterns.
  • Faster code execution: In certain situations, JavaScript engines can optimize switch statements, leading to faster code execution when compared to a series of if-else statements.
  • Easier maintenance: Switch statements make it easier to add, remove, or modify cases, as each case is self-contained within the switch block. In contrast, if-else chains may require more extensive modifications when changes are needed.
  • Default fallback: Switch statements provide an optional default case that can be executed when none of the other cases match the given expression. This feature allows for a clean way to handle unexpected or unknown values.

When to use if-else over switch

  • Complex conditions: If the conditions you are evaluating involve complex logic, multiple variables, or relational and logical operators, if-else patterns provide more flexibility and are better suited for these situations than switch statements.
  • Range-based conditions: When you need to check for a range of values or conditions that are not discrete, if-else patterns offer a better solution, as switch statements are designed for comparing discrete values.
  • Small number of conditions: If you have only a few simple conditions to check, using an if-else pattern can be more straightforward and easier to write than a switch statement.
  • Non-constant cases: Switch statements require constant values for case labels, meaning they cannot be expressions that change at runtime. If you need to evaluate conditions with non-constant values, if-else patterns are the appropriate choice.
  • Evaluating truthy or falsy values: If-else patterns are suitable when you need to check if a value is truthy or falsy. Switch statements are not designed for this type of evaluation and would require more verbose code to accomplish the same result.
  • Early exit conditions: If you have an early exit condition where further evaluation is unnecessary once a certain condition is met, if-else patterns can be more efficient. With a switch statement, all cases are evaluated, even if an early match is found (unless you use a “break” statement).

Deciding on switch or if-else

Both switch and if-else solve similar problems and have advantages and disadvantages based on your use cases. To help you make your decision, I’ve created a simple switch statement:

The switch statement provides additional functionality and concepts that can be used to improve the performance, readability, and conciseness of your code.

The default case

The default case in a switch statement is executed when none of the other cases match the provided expression. It serves as a fallback to handle unexpected or unknown values, ensuring a response is provided even if there’s no matching case.

The break keyword

The break keyword is used in a switch statement to exit the switch block once a matching case is found and executed. It prevents the code from continuing to execute the remaining cases, ensuring only the correct output is generated.

The Fall-Through technique

A case cannot have more than one condition in a switch statement. To incorporate multiple conditions in one case, consider using the fall-through technique. Not only does it save you time, it ensure you don’t repeat yourself .

Fall-through in a switch statement occurs when you intentionally omit the break keyword in a case, allowing the code execution to continue to the next case(s) until a break is encountered or the end of the switch block is reached. This can be useful when multiple cases share the same output or action.

Multiple cases executing (Forgetting to use the break statement)

A frequent mistake when using switch statements is not including the break statement after each case. This error results in unintentional fall-through, executing multiple cases instead of just the desired one.

How to fix it: Add a break statement after each case to prevent fall-through.

Incorrect Comparison Values and Types

Switch statements use strict comparison, which can lead to unexpected results when comparing different data types. In the example below, the string "2" is not equal to the number 2 . This pitfall might cause your cases not to execute as intended.

How to fix: Consider the type of your variables and remember it will be evaluated strictly. TypeScript may help if you’re working on larger projects.

Scoping issues

A common pitfall in switch statements is declaring variables without block scope or incorrect scopes, causing them to be accessible in other cases, or creating syntax errors. You may experience an Uncaught SyntaxError: ... if you try to redeclare the same variable in multiple clauses.

  • For common variables you intend to use in all cases, declare it with let before your switch statement, or;
  • Scope your clauses as block scope (i.e. wrap your clauses with parentheses { ... } )

Block scope your clauses:

Now that you know what a switch statement is, how it works, and when to use it, it’s time to start implementing it! I hope you’ve enjoyed this article. Join us over on the SitePoint Community if you have any questions about this piece or JavaScript in general.

What is the purpose of a JavaScript switch statement?

A JavaScript switch statement is a type of conditional statement that allows the execution of different code blocks based on a test expression’s value. It is particularly useful when you have multiple conditions to check. Instead of using multiple if-else statements, which can make the code lengthy and complex, a switch statement provides a more readable and organized way to control the flow of the program.

How does a switch statement work in JavaScript?

A switch statement in JavaScript works by comparing a given expression with multiple possible cases. It starts by evaluating an expression to produce a value. Then, it compares this value with the values of different cases. If a match is found, the block of code associated with that case is executed. If no match is found, and a default case is provided, the code associated with the default case is executed.

Can I use a switch statement for multiple cases in JavaScript?

Yes, you can use a switch statement for multiple cases in JavaScript. In fact, this is one of the main advantages of using a switch statement. It allows you to handle multiple conditions by defining different cases. Each case is associated with a block of code, which is executed if the case’s value matches the value of the switch expression.

How do I use a default case in a JavaScript switch statement?

In a JavaScript switch statement, the default case is used when none of the other cases match the switch expression’s value. It is similar to the “else” clause in an if-else statement. To use a default case, you simply write the keyword “default”, followed by a colon, and then the block of code you want to execute.

Can I use strings in a JavaScript switch statement?

Yes, you can use strings in a JavaScript switch statement. The switch expression and the case values can be of any data type, including strings. When the switch statement evaluates the expression, it will compare the resulting value with the values of the cases. If a match is found, the corresponding block of code is executed.

Can I use a switch statement with arrays in JavaScript?

While you can’t directly use a switch statement with arrays in JavaScript, you can use a switch statement inside a loop that iterates over an array. In each iteration, you can use the switch statement to perform different actions based on the current array element’s value.

How do I break out of a switch statement in JavaScript?

To break out of a switch statement in JavaScript, you use the “break” keyword. This keyword is usually placed at the end of each case’s code block. When the JavaScript interpreter encounters the “break” keyword, it immediately exits the switch statement, regardless of whether there are more cases to check.

Can I use a switch statement inside a function in JavaScript?

Yes, you can use a switch statement inside a function in JavaScript. This can be useful when the function’s behavior depends on one of its parameters. By using a switch statement, you can define different code blocks for different parameter values, making the function more flexible and reusable.

Can I use a switch statement with objects in JavaScript?

While you can’t directly use a switch statement with objects in JavaScript, you can use a switch statement to perform different actions based on an object’s property value. You would first need to access the object’s property, and then use that value in the switch statement.

Can I nest switch statements in JavaScript?

Yes, you can nest switch statements in JavaScript. This means you can have a switch statement inside another switch statement. This can be useful when you need to perform more complex conditional logic. However, nested switch statements can make the code more difficult to read and understand, so they should be used sparingly.

Mark is the General Manager of SitePoint.com. He loves to read and write about technology, startups, programming languages, and no code tools.

SitePoint Premium

IMAGES

  1. Switch Case & Assignment

    java switch case assignment

  2. P10 switch case statement Beginner Java & AP Computer Science

    java switch case assignment

  3. Java String Switch Case Example

    java switch case assignment

  4. Switch Case in Java with Example

    java switch case assignment

  5. Java switch case

    java switch case assignment

  6. Last Minute Java Switch Case Tutorial

    java switch case assignment

VIDEO

  1. Switch Case in Core Java

  2. java switch case interview questions

  3. JAVA SWITCH (bisaya)

  4. Java Switch Case

  5. Switch case in java

  6. Java Switch Case

COMMENTS

  1. Switch Statements in Java

    The switch statement in Java is a multi-way branch statement. In simple words, the Java switch statement executes one statement from multiple conditions. It is like an if-else-if ladder statement. It provides an easy way to dispatch execution to different parts of code based on the value of the expression. The expression can be a byte, short ...

  2. The switch Statement (The Java™ Tutorials > Learning the Java Language

    A statement in the switch block can be labeled with one or more case or default labels. The switch statement evaluates its expression, then executes all statements that follow the matching case label. You could also display the name of the month with if-then-else statements: System.out.println("January");

  3. Java Switch

    switch(expression) { case x: // code block break; case y: // code block break; default: // code block } This is how it works: The switch expression is evaluated once. The value of the expression is compared with the values of each case. If there is a match, the associated block of code is executed. The break and default keywords are optional ...

  4. Java switch Statement (With Examples)

    break Statement in Java switch...case. Notice that we have been using break in each case block.... case 29: size = "Small"; break; ... The break statement is used to terminate the switch-case statement. If break is not used, all the cases after the matching case are also executed. For example,

  5. Java Switch Statement

    switch(expression) { case 1: // code block break; case 2: // code block break; case 3: // code block break; default: // code block } Above, the expression in the switch parenthesis is compared to each case. When the expression is the same as the case, the corresponding code block in the case gets executed.

  6. Switch Case statement in Java with example

    The syntax of Switch case statement looks like this - switch (variable or an integer expression) { case constant: //Java code ; case constant: //Java code ; default: //Java code ; } Switch Case statement is mostly used with break statement even though it is optional. We will first see an example without break statement and then we will ...

  7. Switch Expressions

    Like all expressions, switch expressions evaluate to a single value and can be used in statements. They may contain "case L ->" labels that eliminate the need for break statements to prevent fall through.You can use a yield statement to specify the value of a switch expression.. For background information about the design of switch expressions, see JEP 361.

  8. Java switch Statements

    A Java switch statement enables you to select a set of statements to execute based on the value of some variable. This is in effect somewhat similar to a Java if statement, although the Java switch statement offers a somewhat more compressed syntax, and slightly different behaviour and thus possibilities. In this Java switch tutorial I will explain both how the original Java switch instruction ...

  9. Java Switch

    The Java switch statement executes one statement from multiple conditions. It is like if-else-if ladder statement. The switch statement works with byte, short, int, long, enum types, String and some wrapper types like Byte, Short, Int, and Long. Since Java 7, you can use strings in the switch statement. In other words, the switch statement ...

  10. Java switch case with examples

    This article helps you understand and use the switch case construct in Java with code examples. The switch-case construct is a flow control structure that tests value of a variable against a list of values. Syntax of this structure is as follows: switch (expression) { case constant_1: // statement 1 break; case constant_2: // statement 2 break; case constant_3: // statement 3 break; //...

  11. Declaring and initializing variables within Java switches

    The scope of a label of a labeled statement is the immediately contained Statement. In other words, case 1, case 2 are labels within the switch statement. break and continue statements can be applied to labels. Because labels share the scope of the statement, all variables defined within labels share the scope of the switch statement.

  12. Implementing Switch and Case in Java: Syntax and Use Cases

    System.out.println('The selected month is: ' + monthString); The program SwitchCaseDemo is a simple demonstration of how to implement the switch and case statements in Java. The main objective here is to convert an integer representing a month (1-12) into its corresponding month name as a string and then print it out.

  13. Pattern Matching for Switch

    The Java SE 17 release introduces pattern matching for switch expressions and statements ( JEP 406) as a preview feature. Pattern matching provides us more flexibility when defining conditions for switch cases. In addition to case labels that can now contain patterns, the selector expression is no longer limited to just a few types.

  14. Java 14: Switch Expressions Enhancements Examples

    Java 14 adds a new form of switch label "case L ->" which allows multiple constants per case and returns a value for the whole switch-case block so it can be used in expressions (switch expressions). And the yield keyword is used to return value from a switch expression. Now, let's see code examples to understand these enhancements for ...

  15. syntax

    Just trying to figure out how to use many multiple cases for a Java switch statement. Here's an example of what I'm trying to do: switch (variable) { case 5..100: doSomething(); break; } versus having to do: switch (variable) { case 5: case 6: etc. case 100: doSomething(); break; }

  16. Modern Java Switch Expressions

    In this blog, I will cover some improvements of switch. The old syntax dates back to the early day of Java, and its handling is a bit cumbersome. Let's look at the newer, slightly modified syntax for switch, called Switch Expressions. With it, case distinctions can be formulated much more elegantly than before. Introductory example

  17. Java Switch Statement

    Switch Statement. The switch statement is Java's multiway branch statement. It provides an easy way to dispatch execution to different parts of your code based on the value of an expression. Here is the general form of a switch statement: switch (expression) { case value1: // statement sequence break; case value2: // statement sequence break ...

  18. Switch Case In Java: A Complete Guide With Examples

    There are a certain rules one must keep in mind while declaring a switch case in java. Following are a certain points to remember while writing a switch case in java. We cannot declare duplicate values in a switch case. The values in the case and the data type of the variable in a switch case must be same. Variables are not allowed in a case ...

  19. Pattern Matching for switch Expressions and Statements

    A switch statement transfers control to one of several statements or expressions, depending on the value of its selector expression. In earlier releases, the selector expression must evaluate to a number, string or enum constant, and case labels must be constants. However, in this release, the selector expression can be any reference type or an int type but not a long, float, double, or ...

  20. What is Switch Case in Java and How to Use Switch Statement in Java

    The switch statement or switch case in java is a multi-way branch statement. Based on the value of the expression given, different parts of code can be executed quickly. The given expression can be of a primitive data type such as int, char, short, byte, and char. With JDK7, the switch case in java works with the string and wrapper class and ...

  21. Using switch in Java to assign additional values

    String prize = "Prize #2"; When you Assign a variable in above manner i.e. data type followed by variable name compiler assumes that you want to define a new variable with some value. Instead, you should define it once. String prize = ""; // Data type followed by variable name is to define new variable.

  22. Mastering the JavaScript switch Statement

    The JavaScript switch statement is a way to make decisions in your code based on different conditions. It is a more organized and concise alternative to using multiple if-else statements. The ...

  23. switch statement

    I am making an expression parser for a calculator. The expressions will contain a variable, for instance, a user could enter "x + 2", or "y^2". I have a switch statement, and one of the cases in switch statement performs a certain action when it detects a variable: