Pattern Matching for Switch

Last updated: May 11, 2024

java switch variable assignment

  • Java Statements

announcement - icon

It's finally here:

>> The Road to Membership and Baeldung Pro .

Going into ads, no-ads reading , and bit about how Baeldung works if you're curious :)

Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, visit the documentation page .

You can also ask questions and leave feedback on the Azure Container Apps GitHub page .

Java applications have a notoriously slow startup and a long warmup time. The CRaC (Coordinated Restore at Checkpoint) project from OpenJDK can help improve these issues by creating a checkpoint with an application's peak performance and restoring an instance of the JVM to that point.

To take full advantage of this feature, BellSoft provides containers that are highly optimized for Java applications. These package Alpaquita Linux (a full-featured OS optimized for Java and cloud environment) and Liberica JDK (an open-source Java runtime based on OpenJDK).

These ready-to-use images allow us to easily integrate CRaC in a Spring Boot application:

Improve Java application performance with CRaC support

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

To learn more about Java features on Azure Container Apps, you can get started over on the documentation page .

And, you can also ask questions and leave feedback on the Azure Container Apps GitHub page .

Whether you're just starting out or have years of experience, Spring Boot is obviously a great choice for building a web application.

Jmix builds on this highly powerful and mature Boot stack, allowing devs to build and deliver full-stack web applications without having to code the frontend. Quite flexibly as well, from simple web GUI CRUD applications to complex enterprise solutions.

Concretely, The Jmix Platform includes a framework built on top of Spring Boot, JPA, and Vaadin , and comes with Jmix Studio, an IntelliJ IDEA plugin equipped with a suite of developer productivity tools.

The platform comes with interconnected out-of-the-box add-ons for report generation, BPM, maps, instant web app generation from a DB, and quite a bit more:

>> Become an efficient full-stack developer with Jmix

DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema .

The way it does all of that is by using a design model , a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.

And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.

>> Take a look at DBSchema

Get non-trivial analysis (and trivial, too!) suggested right inside your IDE or Git platform so you can code smart, create more value, and stay confident when you push.

Get CodiumAI for free and become part of a community of over 280,000 developers who are already experiencing improved and quicker coding.

Write code that works the way you meant it to:

>> CodiumAI. Meaningful Code Tests for Busy Devs

The AI Assistant to boost Boost your productivity writing unit tests - Machinet AI .

AI is all the rage these days, but for very good reason. The highly practical coding companion, you'll get the power of AI-assisted coding and automated unit test generation . Machinet's Unit Test AI Agent utilizes your own project context to create meaningful unit tests that intelligently aligns with the behavior of the code. And, the AI Chat crafts code and fixes errors with ease, like a helpful sidekick.

Simplify Your Coding Journey with Machinet AI :

>> Install Machinet AI in your IntelliJ

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

Download the E-book

Do JSON right with Jackson

Get the most out of the Apache HTTP Client

Get Started with Apache Maven:

Working on getting your persistence layer right with Spring?

Explore the eBook

Building a REST API with Spring?

Get started with Spring and Spring Boot, through the Learn Spring course:

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Get started with Spring and Spring Boot, through the reference Learn Spring course:

>> LEARN SPRING

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth , to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project .

You can explore the course here:

>> Learn Spring Security

1. Overview

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. Before pattern matching, switch cases supported only simple testing of a selector expression that needs to match a constant value exactly.

In this tutorial, we will cover three different pattern types that can be applied in switch statements. We’ll also explore some switch specifics, like covering all values, ordering subclasses, and handling null values.

2. Switch Statement

We use switch in Java to transfer control to one of the several predefined case statements. Which statement gets selected depends on the value of the switch selector expression.

In the earlier versions of Java, the selector expression had to be a number, a string, or a constant . Also, the case labels could only contain constants:

In our example, if variable b wasn’t final , the compiler would throw a constant expression required error.

3. Pattern Matching

Pattern matching, in general, was first introduced as a preview feature in Java SE 14.

It was limited to only one form of a pattern – the type pattern. A typical pattern consists of a type name and the variable to bind the result to.

Applying type patterns to the instanceof operator simplifies type checking and casting . Moreover, it enables us to combine both into a single expression:

This built-in language enhancement helps us write less code with enhanced readability.

4. Patterns for Switch

Pattern matching for instanceof became a permanent feature in Java SE 16.

With Java 17, the application of pattern matching now also expands to switch expressions .

However, it is still a preview feature , so we need to enable preview to use it:

4.1. Type Pattern

Let’s look at how type patterns and the instanceof operator can be applied in switch statements.

As an example, we’ll create a method that converts different types to double using if-else statements. Our method will simply return zero if the type is not supported:

We can solve the same problem with less code using type patterns in switch :

In earlier versions of Java, the selector expression was limited to only a few types. However, with type patterns, the switch selector expression can be of any type.

4.2. Guarded Pattern

Type patterns help us transfer control based on a particular type. However, sometimes, we also need to perform additional checks on the passed value.

For example, we may use an if statement to check the length of a String :

We can solve the same problem using guarded patterns. They use a combination of a pattern and a boolean expression:

Guarded patterns enable us to avoid additional if conditions in switch statements. Instead, we can move our conditional logic to the case label .

4.3. Parenthesized Pattern

In addition to having conditional logic in the cases label, parenthesized patterns enable us to group them .

We can simply use parentheses in our boolean expressions when performing additional checks:

By using parentheses, we can avoid having additional if-else statements.

5. Switch Specifics

Let’s now look at a couple of specific cases to consider while using pattern matching in switch .

5.1. Covering All Values

When using pattern matching in switch , the Java compiler will check the type coverage .

Let’s consider an example switch condition accepting any object but covering only the String case:

Our example will result in the following compilation error:

This is because the switch case labels are required to include the type of the selector expression .

The default case label may also be applied instead of a specific selector type.

5.2. Ordering Subclasses

When using subclasses with pattern matching in switch , the order of the cases matters .

Let’s consider an example where the String case comes after the CharSequence case.

Since String is a subclass of CharSequence, our example will result in the following compilation error:

The reasoning behind this error is that there is no chance that the execution goes to the second case since any string object passed to the method would be handled in the first case itself.

5.3. Handling Null Values

In earlier versions of Java, each passing of a null value to a switch statement would result in a NullPointerException .

However, with type patterns, it is now possible to apply the null check as a separate case label :

If there is no null-specific case label, a pattern label of total type will match null values :

We should note that a switch expression cannot have both a null case and a total type case.

Such a switch statement will result in the following compilation error:

Finally, a switch statement using pattern matching can still throw a NullPointerException .

However, it can do so only when the switch block doesn’t have a null-matching case label.

6. Conclusion

In this article, we explored pattern matching for switch expressions and statements, a preview feature in Java SE 17 . We saw that by using patterns in case labels, that selection is determined by pattern matching rather than a simple equality check.

In the examples, we covered three different pattern types that can be applied in switch statements. Finally, we explored a couple of specific cases, including covering all values, ordering subclasses, and handling null values.

As always, the complete source code is available over on GitHub .

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode , for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

Looking for the ideal Linux distro for running modern Spring apps in the cloud?

Meet Alpaquita Linux : lightweight, secure, and powerful enough to handle heavy workloads.

This distro is specifically designed for running Java apps . It builds upon Alpine and features significant enhancements to excel in high-density container environments while meeting enterprise-grade security standards.

Specifically, the container image size is ~30% smaller than standard options, and it consumes up to 30% less RAM:

>> Try Alpaquita Containers now.

Explore the secure, reliable, and high-performance Test Execution Cloud built for scale. Right in your IDE:

Basically, write code that works the way you meant it to.

AI is all the rage these days, but for very good reason. The highly practical coding companion, you'll get the power of AI-assisted coding and automated unit test generation . Machinet's Unit Test AI Agent utilizes your own project context to create meaningful unit tests that intelligently aligns with the behavior of the code.

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

RWS Course Banner

Learn Java practically and Get Certified .

Popular Tutorials

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

  • Get Started With Java
  • Your First Java Program
  • Java Comments

Java Fundamentals

  • Java Variables and Literals
  • Java Data Types (Primitive)
  • Java Operators
  • Java Basic Input and Output
  • Java Expressions, Statements and Blocks

Java Flow Control

  • Java if...else Statement
  • Java Ternary Operator
  • Java for Loop
  • Java for-each Loop
  • Java while and do...while Loop

Java break Statement

Java continue Statement

Java switch Statement

  • Java Arrays
  • Java Multidimensional Arrays
  • Java Copy Arrays

Java OOP(I)

  • Java Class and Objects
  • Java Methods
  • Java Method Overloading
  • Java Constructors
  • Java Static Keyword
  • 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 Abstract Class and Abstract Methods
  • Java Interface
  • Java Polymorphism
  • Java Encapsulation

Java OOP(III)

  • Java Nested and Inner Class
  • Java Nested Static Class
  • Java Anonymous Class
  • Java Singleton Class
  • Java enum Constructor
  • Java enum Strings
  • Java Reflection
  • Java Package
  • 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 ArrayList
  • Java Vector
  • Java Stack Class
  • Java Queue Interface
  • Java PriorityQueue
  • Java Deque Interface
  • Java LinkedList
  • Java ArrayDeque
  • Java BlockingQueue
  • 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 Class
  • Java EnumSet
  • Java LinkedHashSet
  • Java SortedSet Interface
  • Java NavigableSet Interface
  • Java TreeSet
  • Java Algorithms
  • Java Iterator Interface
  • Java ListIterator Interface

Java I/o Streams

  • Java I/O Streams
  • Java InputStream Class
  • Java OutputStream Class
  • Java FileInputStream Class
  • Java FileOutputStream Class
  • Java ByteArrayInputStream Class
  • Java ByteArrayOutputStream Class
  • Java ObjectInputStream Class
  • Java ObjectOutputStream Class
  • Java BufferedInputStream Class
  • Java BufferedOutputStream Class
  • Java PrintStream Class

Java Reader/Writer

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

Additional Topics

  • Java Keywords and Identifiers
  • Java Operator Precedence
  • Java Bitwise and Shift Operators
  • Java Scanner Class
  • Java Type Casting
  • Java Wrapper Class
  • Java autoboxing and unboxing
  • Java Lambda Expressions
  • Java Generics
  • Nested Loop in Java
  • Java Command-Line Arguments

Java Tutorials

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

Before we wrap up, let’s put your knowledge of Java switch Statement (With Examples) to the test! Can you solve the following challenge?

Write a function to perform basic arithmetic operations.

  • The given operations are: addition + , subtraction - , multiplication * , and division / .
  • Return the result of the operation specified by the operator op on the numbers num1 and num2 .
  • For example, if num1 = 5 , op = '+' and num2 = 3 , the expected output is 8 .

Sorry about that.

Our premium learning platform, created with over a decade of experience and thousands of feedbacks .

Learn and improve your coding skills like never before.

  • Interactive Courses
  • Certificates
  • 2000+ Challenges

Related Tutorials

Java Tutorial

  • Java Tutorial
  • What is Java?
  • Installing the Java SDK
  • Your First Java App
  • Java Main Method
  • Java Project Overview, Compilation and Execution
  • Java Core Concepts
  • Java Syntax
  • Java Variables
  • Java Data Types
  • Java Math Operators and Math Class
  • Java Arrays
  • Java String
  • Java Operations
  • Java if statements
  • Java Ternary Operator

Java switch Statements

  • Java instanceof operator
  • Java for Loops
  • Java while Loops
  • Java Classes
  • Java Fields
  • Java Methods
  • Java Constructors
  • Java Packages
  • Java Access Modifiers
  • Java Inheritance
  • Java Nested Classes
  • Java Record
  • Java Abstract Classes
  • Java Interfaces
  • Java Interfaces vs. Abstract Classes
  • Java Annotations
  • Java Lambda Expressions
  • Java Modules
  • Java Scoped Assignment and Scoped Access
  • Java Exercises

Java Switch Video Tutorials

Java switch statement example, the if statement equivalent, switch on parameters, switch on byte, short and int, switch on char, switch on string, switch on java enum, multiple values per case statement, java switch yield instruction, switch expression use cases.

Jakob Jenkov
Last update: 2020-02-10

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 works, as well as the modifications to the switch instruction with the ability to switch on Java enums , Java Strings , and finally the new switch expression syntax that was added in Java 12 and improved in Java 13.

If you prefer video, I have created two videos that explain the basic Java switch statement and the Java switch expressions.

Let us start with a Java switch statement code example:

This switch example first creates a variable named amount and assigns the value 9 to it.

Second, the example "switches" on the value of the amount variable. Inside the switch statement are 3 case statements and a default statement.

Each case statement compares the value of the amount variable with a constant value. If the amount variable value is equal to that constant value, the code after the colon (:) is executed. Notice the break keyword after each statement. If no break keyword was place here, the execution could continue down the rest of the case statements until a break is met, or the end of the switch statement is reached. The break keyword makes execution jump out of the switch statement.

The default statement is executed if no case statement matched the value of the amount variable. The default statement could also be executed if the case statements before it did not have a break command in the end. You don't need a default statement. It is optional.

The Java switch example shown in the beginning is equivalent to the following set of Java if statements :

While it looks almost the same, there are situations where using a Java switch statement is easier, and faster. Also, the new Java switch expression added in Java 12 (see later in this tutorial) makes some constructs possible with a switch statement that are not possible with an if-statement.

In the example shown in the beginning of this Java switch tutorial we declared an int variable and immediately set is value to 9. In a real life Java application you would most likely not do that. Instead you would be switching on the value of an input parameter of a method, or on a value read from a file, over the network etc. Here is an example of switching on a method parameter:

Switch on byte, short, char, int, String, or enum's

As you have seen, the switch statement switches on a variable. Before Java 7 this variable has to be numeric and must be either a byte , short , char or int . From Java 7 the variable can also be a String It is also possible switch on a Java enum variable. In the following sections I will show you examples of how to switch on various different Java types.

You can switch on a Java byte , short or int as shown in the following examples:

Notice that the only thing that is different between the above examples is the data type of the method parameter size . Everything else is the same.

It is also possible to switch on a Java char value. Here is an example of switching on a char parameter:

From Java 7 and forward it is possible to use switch on a Java String too. Here is an example of a Java switch on a String :

It is also possible to switch on a Java enum . Here is a Java example that creates a Java enum and then uses it in a switch statement:

Multiple case statements for same operation

In case you want the same operation executed for multiple case statements, you write it like this:

Notice how the first case statement does not have any operation after the colon. The result of this is, that execution just " falls through " to the operation of the next case statement ( and the next etc.) until a break is met. The next break statement is after the second case statement. That means, that for both the first and second case statement, the same operation is executed - that of the second case statement.

From Java 13 and forward you can also have multiple values per case statement, instead of having multiple case statements falling through to the next. Here is the example from the previous section rewritten to use multiple values in a single state statement:

Notice how the multiple values for the first case statement are separated by a comma.

Java switch Expressions

Java 12 added the switch expression as experimental feature. A Java switch expression a switch statement which can return a value. Thus, it can be evaluated as an expression, just like other Java expressions (which are also evaluated to a value). In this section I will show you how the Java switch expressions of Java 12 works.

Remember, I have a video version of the Java switch expression part of this tutorial here:

Here is first a Java switch expression example:

This Java switch expression example converts a value between 0 and 15 to a hexadecimal digit character.

Notice how the colon ( : ) after each case statement has been replaced with a -> operator. This operator is used inside of switch expressions to signal to the Java compiler that this case statement selects a return value for the switch expression, rather than selecting a block of code to execute.

Notice also, that the case statements have no break keyword after them. Since the value selected with the -> operator is interpreted as the return value of the switch expression, the break after each statement is implicit (unnecessary actually). You can also think of the -> as a return statement which returns a value from the switch expression, and thus breaks the execution of the switch expression.

Finally, notice how the digitInHex variable is assigned the return value of the switch expression. This is how you capture the output of a Java switch expression. You could also have returned its value as a return value from a method, like this:

The Java switch expression also works with Java String values. Here is a Java switch expression example using Strings to switch on:

This example resolves a token type (integer value) based on the values of a String token.

From Java 13 you can use the Java switch yield instruction to return a value from a Java switch expression instead of using the arrow operator ( -> ). Here is an example of the Java switch yield instruction looks:

The Java switch expressions are useful in use cases where you need to obtain a value based on another value. For instance, when converting between number values and characters, as shown in the example above.

Java switch expressions are also useful when parsing characters into values, or String tokens into integer token types. In general, whenever you need to resolve one value to another.

Jakob Jenkov

Java Generics

  • Watch & Listen
  • Oracle University

Previous in the Series: Branching with Switch Statements

Branching with Switch Expressions

Modifying the switch syntax.

In Java SE 14 you can use another, more convenient syntax for the switch keyword: the switch expression.

Several things have motivated this new syntax.

  • The default control flow behavior between switch labels is to fall through. This syntax is error-prone and leads to bugs in applications.
  • The switch block is treated as one block. This may be an impediment in the case where you need to define a variable only in one particular case .
  • The switch statement is a statement. In the examples of the previous sections, a variable is given a value in each case . Making it an expression could lead to better and more readable code.

The syntax covered in the previous section, known as switch statement is still available in Java SE 14 and its semantics did not change. Starting with Java SE 14 a new syntax for the switch is available: the switch expression .

This syntax modifies the syntax of the switch label. Suppose you have the following switch statement in your application.

With the switch expression syntax, you can now write it in the following way.

The syntax of switch label is now case L -> . Only the code to the right of the label is executed if the label is matched. This code may be a single expression, a block, or a throw statement. Because this code is one block, you can define variables in it that are local to this particular block.

This syntax also supports multiple constants per case, separated by commas, as shown on the previous example.

Producing a Value

This switch statement can be used as an expression. For instance, the example of the previous section can be rewritten with a switch statement in the following way.

If there is only one statement in the case block, the value produced by this statement is returned by the switch expression.

The syntax in the case of a block of code is a little different. Traditionally, the return keyword is used to denote the value produced by a block of code. Unfortunately this syntax leads to ambiguity in the case of the switch statement. Let us consider the following example. This code does not compile, it is just there as an example.

The block of code executed in the case where quarter is equal to 0 needs to return a value. It uses the return keyword to denote this value. If you take a close look at this code, you see that there are two return statements: one in the case block, and another one in the method block. This is where the ambiguity lies: one may be wondering what is the semantics of the first return . Does it mean that the program exits the method with this value? Or does it leave the switch statement? Such ambiguities lead to poor readability and error-prone code.

A new syntax has been created to solve this ambiguity: the yield statement. The code of the previous example should be written in the following way.

The yield statement is a statement that can be used in any case block of a switch statement. It comes with a value, that becomes the value of the enclosing switch statement.

Adding a Default Clause

Default clauses allow your code to handle cases where the selector value does not match any case constant.

The cases of a switch expression must be exhaustive. For all possible values, there must be a matching switch label. Switch statements are not required to be exhaustive. If the selector target does not match any switch label, this switch statement will not do anything, silently. This may be a place for bugs to hide in your application, something you want to avoid.

In most of the cases, exhaustiveness can be achieved using a default clause; however, in the case of an enum switch expression that covers all known constants, you do not need to add this default clause.

There is still a case that needs to be dealt with. What would happen if someone adds an enumerated value in an enumeration, but forget to update the switch statements on this enumeration? To handle this case, the compiler adds a default clause for you in exhaustive switch statements. This default clause will never be executed in normal cases. It will be only if an enumerated value has been added, and will throw an IncompatibleClassChangeError .

Handling exhaustiveness is a feature of switch expressions that is not provided by traditional switch statements and that is used in other cases than switch on enumerated values.

Writing Colon Case in Switch Expressions

A switch expression can also use a traditional case block with case L: . In this case the fall through semantics does apply. Values are yielded using the yield statement.

Dealing with Null Values

So far, switch statements do not accept null selector values. If you try to switch on a null value you will get a NullPointerException .

Java SE 17 has a preview feature that enhances switch expressions to allow for null values, so you can expect this situation to change.

In this tutorial

Last update: September 22, 2021

Welcome! This site is currently in beta. Get 10% off everything with promo code BETA10.

Switch Statements

  • Introduction

Example of Switch in Java

When to use the switch statement, experiment with switch statements.

The switch statement is another decision-making statement. Logically, the switch statement is very similar to an if/else ladder. The switch statement can have several execution paths; however, it always only evaluates one path.

How to Use Switch in Java

The switch statement utilizes several keywords for its operation, and each one is explained below.

Each possible execution path in a switch statement is denoted with the case keyword. Each case contains a value that is compared with the switch value, and if both values match, then the code in the respective case block will be run.

A switch statement can have as many case sections as you want.

The case blocks almost always end with the ' break ' keyword inside each case (and default ) section. This tells the program to exit the switch and continue with the rest of the program when the proper case has been identified. There is one exception to this rule, which will be covered shortly.

Instead of ending a switch statement with a case , you can end it with the default keyword. The default block will execute if none of the case values are matched.

Here is an example switch statement:

The switch statement is best used when there are a finite number of outcomes, such as hours in a day, months in a year, or floors an elevator can visit.

Please demonstrate the use of a switch statement below. Use a System.out.println() statement for each case so you can validate which case is triggered. Be sure to include break statements in each case. Once you've got that done, remove all the break statements from each case and run the program again. What happens when you don't use break statements? See the example below for additional insights.

As you may have noticed, there is an interesting, intentional behavior with switch statements when the break keyword is not used. Essentially, after a case is triggered, if there is no break statement, each subsequent case will be triggered as well. This is great for situations such as membership levels. For instance, imagine that a business has "bronze", "gold", and "platinum" membership levels. The "bronze" level is the base package. The "gold" level includes everything in "bronze" plus a few more features. And the "platinum" package includes everything in "gold" plus a few more features. Experiment with this scenario in the code editor below.

Summary: Java Switch Statement

  • The switch statement contains multiple execution paths, but only one will be executed
  • The case keyword defines the value to be matched to enter a possible execution path
  • The break keyword ends each case section to tell the program to exit the switch statement
  • The default section will be executed if no case value was matched

Here's the syntax for the switch statement, where you can substitute the variables starting with your_ with your values.

We Love Servers.

  • WHY IOFLOOD?
  • BARE METAL CLOUD
  • DEDICATED SERVERS

Java Switch Statement: Guide to Multiple Conditions

representation of Java switch statement with flowchart elements

Ever felt like you’re wrestling with understanding the switch statement in Java? You’re not alone. Many developers find the concept of switch statements a bit daunting. Think of the switch statement in Java as a traffic controller – directing the flow of your code based on specific conditions.

Switch statements are a powerful way to control the flow of your code, making them extremely popular for handling multiple conditions in a more readable and efficient way compared to if-else statements.

In this guide, we’ll walk you through the process of using switch statements in Java, from the basics to more advanced techniques. We’ll cover everything from understanding the basic syntax, handling different types of switch cases, to troubleshooting common issues.

Let’s dive in and start mastering the Java switch statement!

TL;DR: How Do I Use the Switch Statement in Java?

The switch statement in Java is used to select one of many code blocks to be executed: switch (variableToBeSwitched) . It’s a powerful tool for controlling the flow of your code, especially when you have multiple conditions to handle.

Here’s a simple example:

In this example, we have a switch statement that checks the value of the variable day . Depending on the value, it executes a different code block. If day is 1, it prints ‘Monday’. If day is 2, it prints ‘Tuesday’. In our case, day is 3, so none of the cases match and nothing is printed.

This is just a basic way to use the switch statement in Java, but there’s much more to learn about controlling the flow of your code. Continue reading for more detailed information and advanced usage scenarios.

Table of Contents

Decoding the Basic Syntax of Java Switch Statement

Leveraging switch statements: beyond the basics, exploring alternatives to java switch statement, common pitfalls and best practices with java switch statement, understanding control flow statements in java, applying java switch statement in real-world projects, wrapping up: mastering java switch statement.

The switch statement in Java is a 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’s the basic syntax:

The switch keyword is followed by an expression in parentheses (this can be a variable or a calculated value). The result of this expression is then compared with the values for each case in the structure. If there’s a match, the block of code associated with that case is executed.

The break keyword is used after each case to terminate the statement sequence. If break is not used, all cases after the correct one (including the default case) are executed until a break is encountered.

Let’s look at a practical example:

In this example, the switch expression is num , which has a value of 2. The code block under case 2 is executed, and ‘Two’ is printed. If num were not 1 or 2, the default case would be executed, and ‘Not one or two’ would be printed.

As you become more comfortable with the basic usage of the switch statement in Java, you can start to explore some of its more advanced applications. Two such applications include nested switch statements and using switch with string variables. Let’s dive into these topics.

Nested Switch Statements

Just like you can nest if-else statements, you can also nest switch statements. This means you can have a switch statement inside another switch statement. Here’s how you can do it:

In this example, we have an outer switch statement that checks the value of outer . Inside the case where outer is ‘A’, we have another switch statement that checks the value of inner . This allows us to handle more complex conditions.

Using Switch with String Variables

Starting from Java 7, you can use switch statements with string variables. This can be very useful when you want to perform different actions based on the value of a string. Here’s an example:

In this example, the switch statement checks the value of the string day . Depending on the value, it prints a different message. This is a powerful feature that can greatly simplify your code when dealing with string conditions.

While the switch statement is a powerful tool for controlling the flow of your code, Java provides other control flow statements that can be used as alternatives. Two of these are if-else statements and the ternary operator. Let’s explore these alternatives and compare their benefits and drawbacks to the switch statement.

If-Else Statements

The if-else statement is the most basic way to control the flow of your code. It’s more verbose than the switch statement, but it can handle more complex conditions. Here’s an example:

This code does the same thing as our previous switch statement example, but it uses if-else statements instead. If-else statements are more flexible than switch statements because they can handle conditions that are not just equality checks. However, they can become unwieldy when there are many conditions to check.

Ternary Operator

The ternary operator is a shorthand way of writing an if-else statement. It’s less readable than both if-else and switch statements, but it can be very concise. Here’s an example:

In this example, we use the ternary operator to check the value of num and assign a different string to result based on that value. The ternary operator can be very useful for simple conditions, but it can become difficult to read with more complex conditions.

In conclusion, while the switch statement is a powerful tool for controlling the flow of your code, there are other options available in Java. Depending on your specific needs, you might find that if-else statements or the ternary operator are more suitable.

While the switch statement in Java is a powerful tool, it can also be a source of bugs if not used correctly. Let’s discuss some of the common issues you might encounter when using the switch statement and how to solve them.

Forgetting the Break Keyword

One of the most common mistakes when using the switch statement is forgetting to include the break keyword at the end of each case. When this happens, Java will continue executing the next case(s) until it encounters a break statement. This is known as ‘fall through’.

Here’s an example:

In this example, we forgot to include a break statement after the first case. As a result, both ‘One’ and ‘Two’ are printed, even though num is 1. To avoid this issue, always remember to include a break statement at the end of each case.

No Default Case

Another common issue is forgetting to include a default case in your switch statement. The default case is executed when none of the other cases match the switch expression. If you don’t include a default case, your switch statement might not do anything if none of the cases match.

In this example, num is 3, which doesn’t match any of the cases in our switch statement. Because we didn’t include a default case, nothing is printed. To avoid this issue, always include a default case in your switch statement.

In conclusion, while the switch statement in Java is a powerful tool, it’s important to use it correctly. By being aware of these common issues and following best practices, you can avoid bugs and write more robust code.

Before we delve deeper into the specifics of the switch statement, it’s essential to grasp the concept of control flow statements in Java. Control flow statements, as the name suggests, control the order in which the code statements are executed. These are the building blocks that allow Java (and indeed, any programming language) to make decisions and carry out repetitive tasks.

In Java, control flow statements are divided into three categories: decision-making statements (like if, if-else, and switch), looping statements (like for, while, and do-while), and branching statements (like break, continue, and return).

The switch statement falls under decision-making statements, allowing your program to choose different paths of execution based on an expression’s outcome.

Grasping the Concept of ‘Fall Through’ in Switch Statements

A unique characteristic of the switch statement in Java is the ‘fall through’ behavior. When a match is found in the case values, and there’s no break statement to terminate the current case, Java will execute all subsequent cases until it encounters a break statement or reaches the end of the switch block.

Here’s an example to illustrate this:

In this example, num is 1, which matches the first case. However, because there’s no break statement after the first case, Java ‘falls through’ to the second case and executes that as well, resulting in both ‘One’ and ‘Two’ being printed.

Understanding this ‘fall through’ behavior is crucial when working with switch statements in Java, as it can lead to unexpected results if not handled correctly.

As we’ve seen, the switch statement is a powerful tool for controlling the flow of your code. But how does it apply to larger, real-world projects? One common use case is creating a simple menu system.

Building a Simple Menu System with Java Switch

Let’s say you’re building a text-based game, and you want to present the player with a list of options. You could use a switch statement to handle the player’s input and execute different code based on their choice. Here’s a simple example:

In this example, we present the user with a menu of options and use a switch statement to handle their input. This is a simple but powerful way to use the switch statement in a real-world project.

Further Resources for Mastering Java Switch

Statement are an integral part of Java Control flow. Their usefulness can be enhanced when used along with loops. To learn more on how to utilize loops for controlling the flow of code, you can Click Here .

If you would like to further enhance your understanding and usage of other statements in Java, consider exploring these additional resources:

  • Conditions in Java – Learn about conditional statements and expressions in Java for decision-making.

Using If-Else in Java – Master the if-else statement for implementing conditional logic and flow control in Java.

Java Tutorials by Oracle cover all aspects of the language, including control flow statements like the switch statement.

Java switch statement by W3Schools provides a clear and easy-to-digest guide on how to use the ‘switch’ statement in Java.

Java Control Flow: Oracle’s Java Documentation provides a more in-depth look at control flow in Java, including a detailed section on switch statements.

In addition to these resources, consider exploring related topics such as loops in Java and exception handling to broaden your Java programming skills.

In this comprehensive guide, we’ve navigated through the intricacies of the switch statement in Java, shedding light on its syntax, usage, and application in various scenarios.

We began with the basics, understanding the fundamental syntax and structure of the switch statement. We then delved deeper, exploring its advanced usage, including nested switch statements and the use of switch with string variables. Along the journey, we also tackled common pitfalls such as forgetting the break keyword and not including a default case, and provided effective solutions to these challenges.

Moreover, we took a detour to discuss alternative approaches to control flow in Java, such as if-else statements and the ternary operator, and compared their benefits and drawbacks to the switch statement. Here’s a quick comparison of these methods:

MethodFlexibilityReadabilityComplexity
Switch StatementModerateHighLow
If-Else StatementsHighModerateModerate
Ternary OperatorLowLowHigh

Whether you’re a beginner just starting out with Java or an intermediate developer looking to refine your skills, we hope this guide has given you a deeper understanding of the switch statement and its usage in Java.

The switch statement, with its ability to simplify complex condition handling, is a powerful tool in your Java toolkit. Now, with the knowledge acquired from this guide, you’re well equipped to use it effectively in your Java programming journey. Happy coding!

About Author

Gabriel Ramuglia

Gabriel Ramuglia

Gabriel is the owner and founder of IOFLOOD.com , an unmanaged dedicated server hosting company operating since 2010.Gabriel loves all things servers, bandwidth, and computer programming and enjoys sharing his experience on these topics with readers of the IOFLOOD blog.

Related Posts

A creative depiction of a shield with a CORS symbol representing web security

java switch variable assignment

Modern Java Switch Expressions

java switch variable 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!

Continue reading

The best programming language for beginners to learn in 2024, how many jobs are available in technology, is software engineering hard, subscribe to devdigest.

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

From developers. For developers.

  • 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.

Switch expressions and enums in Java

4 March 2024

Tags that this post has been filed under.

Last week, I wrote about the four forms of switch in Java . I explained that a switch expression without fallthrough is my favourite, and that I would show you how to combine one with an enumerated type (enum).

I have previously written about enums in JavaScript . Regardless of the language, an enum is a set of named constants. Instead of relying on magic values , you can use an enum to define a set of known values. This makes your code more predictable and less error-prone.

Here’s the switch expression without fallthrough that we looked at last week. Instead of assigning the day variable to a string, let’s examine how we can use an enum to make the switch expression safer.

Switch expressions and enums

In a file called SwitchEnumTest.java , let’s declare a Day enum. By convention, the enum constants should be uppercase.

In the same file, let’s declare the public SwitchEnumTest class. In the body of the main() method, we’ll declare the day variable and assign it to Day.MONDAY . Because the variable is of type Day , the compiler guarantees that it can only be assigned to one of the enum constants (or null ). This means we don’t need a default case clause, because the switch expression covers all possible input values.

Note that the case labels have to be the unqualified names of the enum constants, i.e. MONDAY instead of Day.MONDAY . This is nice because it means less typing, but it’s important to understand that it is a syntax error to use the fully qualified name.

Wrapping up

So there you have it: switch expressions and enums, a beautiful combination. Enums can be used with all four forms of switch , but I think they go particularly well with switch expressions where each branch computes the value for a variable assignment, as Horstmann phrases it in Core Java .

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 variable assignment

Add comment

   

Notify me of follow-up comments

Comments  

Java Development Journal

Java Variables

In this article of Java tutorial, we will inspect the Java variables. We will get a deep understanding of Java variables and how to use them in your application.

Table of Contents

When developing applications, we always use variables throughout the development process because they are one of the basic building blocks of programing. Variables are the core component of the Java programming model.In this tutorial we will get a deeper understanding of the four Java variables that exist in Java and how we can leverage them when developing applications.

We will cover several sub-topics not limited to a detailed explanation of what are variables in Java, how to name variables, variable assignment, type inference, the syntax for creating each variable, an example showing how each variable is implemented using a specific data type, and what aspect of the variables differentiates them.

Variables are used to store data for our application. A variable is a combination of a location in the computer’s memory and an associated name that we can use in our code to refer to the data in that memory location . Specifically, Java variables help us to store state data. State data is data related to the current state of the program as it is running.

1. Java Variable Types

Java provides the following 4 types of variable which we will be covering in details in this section.

  • Instance variables (Non-Static Fields).
  • Class variables (Static Variables).
  • Local variables.

Java Variables

2. Variable Assignment

To declare or define a Java variable, we specify the data type, the name of the variable, and any value we want to store in the variable.For example, here we declare an integer value with the name age that holds the value 42 :

Java Variables

The reason we use the term “variable” is because it is able to vary. After we have declared it, we can easily change the value of the variable as many times as we like. Let’s see this in action:

These lines are referred to as assignment statements (because we are assigning the value on the right to the variable named on the left) and the = sign is called the assignment operator .

We will cover the assignment operators in more details under Java operators.

3. Java Variables Naming Convention

While naming the Java variables, we need to keep in mind certain rule. These rules will be validated by compiler and you will get compile time error in case we don’t follow these rules. Let’ take a closer look at the Java variables naming convention.

  • The Java variable name is case sensitive.
  • Variables names can either start with the dollar sign $ , the underscore _ or a letter.
  • The name that is chosen for a variable may be followed by letters, digits, dollar signs, or underscore characters.
  • Keep variable name descriptive to make the code easier to read and understand.
  • We can’t use java keywords or reserved words as variable names.
  • When the name of the variable contains letters only, use the camel case format to name the variables. The camel case starts with lowercase letters and the following words are capitalized.

When the variable is a constant, the leading and subsequent words should be capitalized and separated by an underscore. For Example:

4. Local Variables

Local variables are variables located in a method and these variables can only be used within the method. The local variables do not have any keywords that differentiates them from other variables apart from the fact that their scope is inside a method.

4.1. Local Variable type Inference

In the Local variable example above, we have created a method named startVehicle() and added a local variable containing a string value:

This declaration can be made much simpler by removing the string initializer String and replacing it with non-null initializer var .To achieve this, the language level must be Java 10 and above. The ` var ` identifier infers the type from the context and helps the developer to write code that is easy to read and understand.We can rewrite the local variable of the method using the var identifier as shown below.

The var identifier can be used as a variable, method, or package name because it is not a keyword but a reserved type name and this means using it as a class or interface will be affected requiring renaming of the class or interface.The different types of variables that can be used with the var identifier include: local variable with initializers, enhance for-loop indexes, index variables declared in traditional for loops, try-with-resources variable, and formal parameter declarations of implicitly typed lambda expressions .

5. Parameters

Parameters are variables that are passed as arguments to methods, constructors, and exception handlers. In the local variable example, we hard coded the value being returned by the method but this value could be coming from an external source such as the user input.

To ensure a value is passed to the method, we add a parameter of type string to the method and this can be separated using a comma delimited list if we have more than one parameter. The value of the parameter will be passed to the method when running the program as shown below.

6. Class Variables (Static Fields)

These are variables declared inside the class and contain a static keyword. This means that the application has one copy of the variable and no matter how many objects are created the variable will only have one copy. The ` final ` keyword is added to indicate that the value of the static variable will never change. This is the reason they are called class variables because they do not belong to any object but to the class.

7. Instance Variable

Each instance of class has its own copy of instance variable. Unlike static variable, instance variables have their own separate copy of instance variable

In this tutorial, we have learned about the Java variables and how to use them when developing our applications. The different subtopics that we have covered include: variable assignment, naming convention of variables, local variable type inference, class variables, local variables, and parameters. Source code for all our articles is available on the GitHub repository .

  • Java Course
  • 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

Java Assignment Operators with Examples

Operators constitute the basic building block of any programming language. Java too provides many types of operators which can be used according to the need to perform various calculations and functions, be it logical, arithmetic, relational, etc. They are classified based on the functionality they provide.

Types of Operators: 

  • Arithmetic Operators
  • Unary Operators
  • Assignment Operator
  • Relational Operators
  • Logical Operators
  • Ternary Operator
  • Bitwise Operators
  • Shift Operators

This article explains all that one needs to know regarding Assignment Operators. 

Assignment Operators

These operators are used to assign values to a variable. The left side operand of the assignment operator is a variable, and the right side operand of the assignment operator is a value. The value on the right side must be of the same data type of the operand on the left side. Otherwise, the compiler will raise an error. This means that the assignment operators have right to left associativity, i.e., the value given on the right-hand side of the operator is assigned to the variable on the left. Therefore, the right-hand side value must be declared before using it or should be a constant. The general format of the assignment operator is, 

Types of Assignment Operators in Java

The Assignment Operator is generally of two types. They are:

1. Simple Assignment Operator: The Simple Assignment Operator is used with the “=” sign where the left side consists of the operand and the right side consists of a value. The value of the right side must be of the same data type that has been defined on the left side.

2. Compound Assignment Operator: The Compound Operator is used where +,-,*, and / is used along with the = operator.

Let’s look at each of the assignment operators and how they operate: 

1. (=) operator: 

This is the most straightforward assignment operator, which is used to assign the value on the right to the variable on the left. This is the basic definition of an assignment operator and how it functions. 

Syntax:  

Example:  

2. (+=) operator: 

This operator is a compound of ‘+’ and ‘=’ operators. It operates by adding the current value of the variable on the left to the value on the right and then assigning the result to the operand on the left. 

Note: The compound assignment operator in Java performs implicit type casting. Let’s consider a scenario where x is an int variable with a value of 5. int x = 5; If you want to add the double value 4.5 to the integer variable x and print its value, there are two methods to achieve this: Method 1: x = x + 4.5 Method 2: x += 4.5 As per the previous example, you might think both of them are equal. But in reality, Method 1 will throw a runtime error stating the “i ncompatible types: possible lossy conversion from double to int “, Method 2 will run without any error and prints 9 as output.

Reason for the Above Calculation

Method 1 will result in a runtime error stating “incompatible types: possible lossy conversion from double to int.” The reason is that the addition of an int and a double results in a double value. Assigning this double value back to the int variable x requires an explicit type casting because it may result in a loss of precision. Without the explicit cast, the compiler throws an error. Method 2 will run without any error and print the value 9 as output. The compound assignment operator += performs an implicit type conversion, also known as an automatic narrowing primitive conversion from double to int . It is equivalent to x = (int) (x + 4.5) , where the result of the addition is explicitly cast to an int . The fractional part of the double value is truncated, and the resulting int value is assigned back to x . It is advisable to use Method 2 ( x += 4.5 ) to avoid runtime errors and to obtain the desired output.

Same automatic narrowing primitive conversion is applicable for other compound assignment operators as well, including -= , *= , /= , and %= .

3. (-=) operator: 

This operator is a compound of ‘-‘ and ‘=’ operators. It operates by subtracting the variable’s value on the right from the current value of the variable on the left and then assigning the result to the operand on the left. 

4. (*=) operator:

 This operator is a compound of ‘*’ and ‘=’ operators. It operates by multiplying the current value of the variable on the left to the value on the right and then assigning the result to the operand on the left. 

5. (/=) operator: 

This operator is a compound of ‘/’ and ‘=’ operators. It operates by dividing the current value of the variable on the left by the value on the right and then assigning the quotient to the operand on the left. 

6. (%=) operator: 

This operator is a compound of ‘%’ and ‘=’ operators. It operates by dividing the current value of the variable on the left by the value on the right and then assigning the remainder to the operand on the left. 

Please Login to comment...

Similar reads.

  • Java-Operators
  • How to Delete Discord Servers: Step by Step Guide
  • Google increases YouTube Premium price in India: Check our the latest plans
  • California Lawmakers Pass Bill to Limit AI Replicas
  • Best 10 IPTV Service Providers in Germany
  • 15 Most Important Aptitude Topics For Placements [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's, java reference, java examples, java variables.

Variables are containers for storing data values.

In Java, there are different types of variables, for example:

  • String - stores text, such as "Hello". String values are surrounded by double quotes
  • int - stores integers (whole numbers), without decimals, such as 123 or -123
  • float - stores floating point numbers, with decimals, such as 19.99 or -19.99
  • char - stores single characters, such as 'a' or 'B'. Char values are surrounded by single quotes
  • boolean - stores values with two states: true or false

Declaring (Creating) Variables

To create a variable, you must specify the type and assign it a value:

Where type is one of Java's types (such as int or String ), and variableName is the name of the variable (such as x or name ). The equal sign is used to assign values to the variable.

To create a variable that should store text, look at the following example:

Create a variable called name of type String and assign it the value " John ". Then we use println() to print the name variable:

Try it Yourself »

To create a variable that should store a number, look at the following example:

Create a variable called myNum of type int and assign it the value 15 :

You can also declare a variable without assigning the value, and assign the value later:

Note that if you assign a new value to an existing variable, it will overwrite the previous value:

Change the value of myNum from 15 to 20 :

Final Variables

If you don't want others (or yourself) to overwrite existing values, use the final keyword (this will declare the variable as "final" or "constant", which means unchangeable and read-only):

Other Types

A demonstration of how to declare variables of other types:

You will learn more about data types in the next section.

Test Yourself With Exercises

Create a variable named carName and assign the value Volvo to it.

Start the Exercise

Get Certified

COLOR PICKER

colorpicker

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]

Top Tutorials

Top references, top examples, get certified.

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

Assign value to variable in Java with Switch Stament [closed]

I am trying to assign value to variable based on case with old Switch case it is not allowing is there any way or should i need to write initialize variable in each single case?

enter image description here

Enchanced Switch is working though as shown in Case0

  • switch-statement

AMR's user avatar

  • 1 Are you asking how to return a value from a switch statement? Your Question is not clear. Edit for clarity. –  Basil Bourque Commented Jan 6 at 8:21
  • 1 Of course, if you're really doing that, it would be a lot better to do: String[] values = { "ZERO", "ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX", "SEVEN", "EIGHT", "NINE" }; and address only that range –  g00se Commented Jan 6 at 10:31

2 Answers 2

Switch expressions.

In Java 14+, use switch expressions to return a value. See JEP 361: Switch Expressions .

word = SEVEN

As another example, move that switch into a method.

Exercise that method:

Basil Bourque's user avatar

If you insist on using the older switch statements (not switch expressions). You would use the yield keyword to return the result as the value of the switch statement.

Note that it does not use break; and that you cannot mix the two different types together (switch statements and switch expressions)

pebble unit's user avatar

Not the answer you're looking for? Browse other questions tagged java switch-statement or ask your own question .

  • The Overflow Blog
  • At scale, anything that could fail definitely will
  • Featured on Meta
  • Announcing a change to the data-dump process
  • Bringing clarity to status tag usage on meta sites
  • What does a new user need in a homepage experience on Stack Overflow?
  • Feedback requested: How do you use tag hover descriptions for curating and do...
  • Staging Ground Reviewer Motivation

Hot Network Questions

  • Are all citizens of Saudi Arabia "considered Muslims by the state"?
  • Is it a date format of YYMMDD, MMDDYY, and/or DDMMYY?
  • What is the significance of the phrase " in the name of the Lord " as in Psalm 124:8?
  • Is there a way to assign multiple meshes to an object and switch between them?
  • How do I learn more about rocketry?
  • Is it possible to travel to USA with legal cannabis?
  • Can I Use A Server In International Waters To Provide Illegal Content Without Getting Arrested?
  • How many ways can you make change?
  • How best to cut (slightly) varying size notches in long piece of trim
  • How would humans actually colonize mars?
  • Does an unseen creature with a burrow speed have advantage when attacking from underground?
  • Can Christian Saudi Nationals Visit Mecca?
  • How to prevent my frozen dessert from going solid?
  • Not a cross, not a word (number crossword)
  • If a Palestinian converts to Judaism, can they get Israeli citizenship?
  • Why is a USB memory stick getting hotter when connected to USB-3 (compared to USB-2)?
  • Citrix published app asks for credentials
  • What does "if you ever get up this way" mean?
  • Fill the grid with numbers to make all four equations true
  • What other marketable uses are there for Starship if Mars colonization falls through?
  • How to reconcile the effect of my time magic spell with my timeline
  • How do I apologize to a lecturer
  • Uniqueness of Neumann series
  • Multiple alien species on Earth at the same time: one species destroys Earth but the other preserves a small group of humans

java switch variable assignment

IMAGES

  1. Java Programming Switch Statement #9

    java switch variable assignment

  2. Switch statement in Java

    java switch variable assignment

  3. switch Statement in Java

    java switch variable assignment

  4. Java

    java switch variable assignment

  5. How to use Switch case Statement in Java with Example

    java switch variable assignment

  6. How to use Switch statement in Java

    java switch variable assignment

VIDEO

  1. JAVA SWITCH (bisaya)

  2. Java Switch Statement

  3. Java switch case

  4. What is a switch statement?

  5. Switch Statement Example 2 (JavaScript)

  6. JAVA TUTORIAL 10 SWITCH PROGRAM IN JAVA

COMMENTS

  1. 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.

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

    Unlike if-then and if-then-else statements, the switch statement can have a number of possible execution paths. A switch works with the byte, short, char, and int primitive data types. It also works with enumerated types (discussed in Enum Types), the String class, and a few special classes that wrap certain primitive types: Character, Byte, Short, and Integer (discussed in Numbers and Strings).

  3. Java switch : variable declaration and scope

    The Scope of variables defined in a switch() statement would be the same as in a normal block wich is surround by {and }. Therefore every variable defined in a switch() statement is visible for the whole block, once it is defined.

  4. Pattern Matching for Switch

    4. Patterns for Switch. Pattern matching for instanceof became a permanent feature in Java SE 16. With Java 17, the application of pattern matching now also expands to switch expressions. However, it is still a preview feature, so we need to enable preview to use it: java --enable-preview -- source 17 PatternMatching.java.

  5. Switch Statements in Java

    In simple words, the Java switch statement executes one statement from multiple conditions. It is an alternative to 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 of type byte, short, char, int, long, enums, String, or wrapper ...

  6. 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 ...

  7. Java switch Statement (With Examples)

    Java Variables and Literals; Java Data Types (Primitive) Java Operators; Java Basic Input and Output; Java Expressions, Statements and Blocks; Java Flow Control. ... 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.

  8. 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 ...

  9. 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 ...

  10. Branching with Switch Expressions

    The syntax covered in the previous section, known as switch statement is still available in Java SE 14 and its semantics did not change. Starting with Java SE 14 a new syntax for the switch is available: the switch expression. This syntax modifies the syntax of the switch label. Suppose you have the following switch statement in your application.

  11. Java Switch Statements

    1. Case. Each possible execution path in a switch statement is denoted with the case keyword. Each case contains a value that is compared with the switch value, and if both values match, then the code in the respective case block will be run. A switch statement can have as many case sections as you want. 2.

  12. Java Switch Statement: Guide to Multiple Conditions

    The switch statement in Java is a 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's the basic syntax: switch (expression) {. case value1: // code to be executed if expression equals value1; break; case value2: // code to be executed if ...

  13. Modern Java Switch Expressions

    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.

  14. 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 ...

  15. Switch expressions and enums in Java

    Switch expressions and enums. In a file called SwitchEnumTest.java, let's declare a Day enum. By convention, the enum constants should be uppercase. In the same file, let's declare the public SwitchEnumTest class. In the body of the main() method, we'll declare the day variable and assign it to Day.MONDAY. Because the variable is of type ...

  16. Java 14: Switch Expressions Enhancements Examples

    This post provides some code examples to help you understand the new features added to the switch-case construct in the Java programming language, since JDK 14.. 1. What's new for switch block in Java 14? 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 ...

  17. Java Variables

    2. Variable Assignment. To declare or define a Java variable, we specify the data type, the name of the variable, and any value we want to store in the variable.For example, here we declare an integer value with the name age that holds the value 42:. int age=42 // int is the data type and age is the variable name.

  18. Java Assignment Operators with Examples

    Note: The compound assignment operator in Java performs implicit type casting. Let's consider a scenario where x is an int variable with a value of 5. int x = 5; If you want to add the double value 4.5 to the integer variable x and print its value, there are two methods to achieve this: Method 1: x = x + 4.5. Method 2: x += 4.5.

  19. Java Variables

    In Java, there are different types of variables, for example: String - stores text, such as "Hello". String values are surrounded by double quotes. int - stores integers (whole numbers), without decimals, such as 123 or -123. float - stores floating point numbers, with decimals, such as 19.99 or -19.99. char - stores single characters, such as ...

  20. Assign value to variable in Java with Switch Stament

    I am trying to assign value to variable based on case with old Switch case it is not allowing is there any way or should i need to write initialize variable in each single case? public static void . ... Assign value to variable in Java with Switch Stament [closed] Ask Question Asked 6 months ago. Modified 6 months ago. Viewed 417 times