Open In App

Switch Statements in Java

Last Updated : 02 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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

It is 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 classes (Integer, Short, Byte, Long).

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

Syntax:

switch(expression)
{
  case value1 :
     // Statements
     break; // break is optional
  
  case value2 :
     // Statements
     break; // break is optional
     ....
     ....
     ....
   default : 
     // default Statement
}

Example: Size Printer Example

Java
public class SizePrinter {

    public static void main(String[] args) {
        int sizeNumber = 2; // Replace with your desired size (1, 2, 3, 4, or 5)

        switch (sizeNumber) {
            case 1:
                System.out.println("Extra Small");
                break;
            case 2:
                System.out.println("Small");
                break;
            case 3:
                System.out.println("Medium");
                break;
            case 4:
                System.out.println("Large");
                break;
            case 5:
                System.out.println("Extra Large");
                break;
            default:
                System.out.println("Invalid size number");
        }
    }
}

Output
Small

Some Important Rules for Java Switch Statements

  • Case values must be constants or literals and of the same type as the switch expression.
  • Duplicate case values are not allowed.
  • The break statement is used to exit from the switch block. It is optional but recommended to prevent fall-through.
  • The default case is optional and executes if no case matches the switch expression. It can appear anywhere within the switch block.

Note: Starting from Java 7, switch statements can use String type values. They can also handle wrapper classes like Integer, Short, Byte, Long.

Flowchart of Switch-Case Statement 

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

switch statement flowchart in java

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

Example: Finding Day

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

Java
// Java program to Demonstrate Switch Case
// with Primitive(int) Data Type

// Class
public class GFG {

    // Main driver method
    public static void main(String[] args)
    {
        int day = 5;
        String dayString;

        // Switch statement with int data type
        switch (day) {

        // Case
        case 1:
            dayString = "Monday";
            break;

        // Case
        case 2:
            dayString = "Tuesday";
            break;

            // Case
        case 3:
            dayString = "Wednesday";
            break;

            // Case
        case 4:
            dayString = "Thursday";
            break;

        // Case
        case 5:
            dayString = "Friday";
            break;

            // Case
        case 6:
            dayString = "Saturday";
            break;

            // Case
        case 7:
            dayString = "Sunday";
            break;

        // Default case
        default:
            dayString = "Invalid day";
        }
        System.out.println(dayString);
    }
}

Output
Friday

Break in switch case Statements

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

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

Example: Switch statement program without multiple breaks

Java
// Java Program to Demonstrate Switch Case
// with Multiple Cases Without Break Statements

// Class
public class GFG {

    // main driver method
    public static void main(String[] args)
    {
        int day = 2;
        String dayType;
        String dayString;

        // Switch case
        switch (day) {

        // Case
        case 1:
            dayString = "Monday";
            break;

        // Case
        case 2:
            dayString = "Tuesday";
            break;

            // Case
        case 3:
            dayString = "Wednesday";
            break;
        case 4:
            dayString = "Thursday";
            break;
        case 5:
            dayString = "Friday";
            break;
        case 6:
            dayString = "Saturday";
            break;
        case 7:
            dayString = "Sunday";
            break;
        default:
            dayString = "Invalid day";
        }

        switch (day) {
            // Multiple cases without break statements

        case 1:
        case 2:
        case 3:
        case 4:
        case 5:
            dayType = "Weekday";
            break;
        case 6:
        case 7:
            dayType = "Weekend";
            break;

        default:
            dayType = "Invalid daytype";
        }

        System.out.println(dayString + " is a " + dayType);
    }
}

Output
Tuesday is a Weekday

Java Nested Switch Statements

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

Example: Nested Switch Statement

Java
// Java Program to Demonstrate
// Nested Switch Case Statement

// Class
public class GFG {

    // Main driver method
    public static void main(String[] args)
    {
        // Custom input string
        String Branch = "CSE";
        int year = 2;

        // Switch case
        switch (year) {

        // Case
        case 1:
            System.out.println(
                "elective courses : Advance english, Algebra");

            // Break statement to hault execution here
            // itself if case is matched
            break;

            // Case
        case 2:

            // Switch inside a switch
            // Nested Switch
            switch (Branch) {

            // Nested case
            case "CSE":
            case "CCE":
                System.out.println(
                    "elective courses : Machine Learning, Big Data");
                break;

            // Case
            case "ECE":
                System.out.println(
                    "elective courses : Antenna Engineering");
                break;

                // default case
                // It will execute if above cases does not
                // execute
            default:

                // Print statement
                System.out.println(
                    "Elective courses : Optimization");
            }
        }
    }
}

Output
elective courses : Machine Learning, Big Data

Java Enum in Switch Statement

Enums in Java are a powerful feature used to represent a fixed set of constants. They can be used in switch statements for better type safety and readability.

Example: Use of Enum in Switch

Java
// Java Program to Illustrate Use of Enum
// in Switch Statement

// Class
public class GFG {

    // Enum
    public enum Day { Sun, Mon, Tue, Wed, Thu, Fri, Sat }

    // Main driver method
    public static void main(String args[])
    {

        // Enum
        Day[] DayNow = Day.values();

        // Iterating using for each loop
        for (Day Now : DayNow) {

            // Switch case
            switch (Now) {

            // Case 1
            case Sun:
                System.out.println("Sunday");

                // break statement that hault further
                // execution once case is satisfied
                break;

            // Case 2
            case Mon:
                System.out.println("Monday");
                break;

            // Case 3
            case Tue:
                System.out.println("Tuesday");
                break;

            // Case 4
            case Wed:
                System.out.println("Wednesday");
                break;

            // Case 5
            case Thu:
                System.out.println("Thursday");
                break;

            // Case 6
            case Fri:
                System.out.println("Friday");
                break;

            // Case 7
            case Sat:
                System.out.println("Saturday");
            }
        }
    }
}

Output
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday

Default statement in Java Switch Case

The default case in a switch statement specifies the code to run if no other case matches. It can be placed at any position in the switch block but is commonly placed at the end.

Example: Writing default in the middle of switch statements:

Java
import java.io.*;

class GFG {
    public static void main (String[] args) {
        int i=2;
          switch(i){
          default:
            System.out.println("Default");
          case 1:
            System.out.println(1);
            break;
          case 2:
            System.out.println(2);
          case 3:
            System.out.println(3);
        
        }
    }
}

Output
2
3

Example: Writing Default at the Beginning of Switch Statements

Java
import java.io.*;

class GFG {
    public static void main(String[] args)
    {
        int i = 5;
        switch (i) {
        default:
            System.out.println("Default");
        case 1:
            System.out.println(1);
            break;
        case 2:
            System.out.println(2);
        case 3:
            System.out.println(3);
        }
    }
}

Output
Default
1

Case label variations

Case labels and switch arguments can be constant expressions. The switch argument can be a variable expression but the case labels must be constant expressions.

Example: Using Variable in Switch Argument

Java
import java.io.*;

class GFG {
    public static void main(String[] args)
    {
        int x = 2;
        switch (x + 1) {
        case 1:
            System.out.println(1);
            break;
        case 1 + 1:
            System.out.println(2);
            break;
        case 2 + 1:
            System.out.println(3);
            break;
        default:
            System.out.println("Default");
        }
    }
}

Output
3

Example: Case Label Cannot Be Variable

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

Java
import java.io.*;

class GFG {
    public static void main(String[] args)
    {
        int x = 2;
        int y = 1;
        switch (x) {
        case 1:
            System.out.println(1);
            break;
        case 2:
            System.out.println(2);
            break;
        case x + y:
            System.out.println(3);
            break;
        default:
            System.out.println("Default");
        }
    }
}
./GFG.java:16: error: constant expression required
          case x+y:
                ^
1 error

Java Wrapper in Switch Statements

Java allows the use of wrapper classes (Integer, Short, Byte, Long, and Character) in switch statements. This provides flexibility when dealing with primitive data types and their corresponding wrapper types.

Example: Using Wrapper Classes

Java
public class WrapperSwitchExample {

    public static void main(String[] args) {
        Integer age = 25;

        switch (age) { // Extract primitive value for switch
            case 25:
                System.out.println("You are 25.");
                break;
            case 30:
                System.out.println("You are 30.");
                break;
            default:
                System.out.println("Age not matched.");
        }
    }
}

Output
You are 25.

Note: Regardless of its placement, the default case only gets executed if none of the other case conditions are met. So, putting it at the beginning, middle, or end doesn’t change the core logic (unless you’re using a less common technique called fall-through).

Example: Using Character Wrapper

Java
public class WrapperSwitchExample {
    public static void main(String[] args) {
        Character ch = 'c';

        switch (ch) { // Extract primitive value for switch
            case 'a':
                System.out.println("You are a.");
                break;
            case 'c':
                System.out.println("You are c.");
                break;
            default:
                System.out.println("Character not matched.");
        }
    }
}

Output
You are c.

Read More:

Exercise:

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

Conclusion

Switch statements in Java are control flow structures that allow you to execute specific blocks of code based on the value of a single expression. They can be considered an alternative to if-else-if statements and are useful for handling multiple conditions in a clean and readable manner.

Java Switch Statements- FAQs

How to use switch statements in Java?

To use switch statement in Java, you can use the following syntax:

switch (expression) {
   case value1:
       // code to execute if expression equals value1
       break;
   case value2:
       // code to execute if expression equals value2
       break;
   // … more cases
   default:
       // code to execute if none of the above cases match
}
 

Can we pass null to a switch?

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

Can you return to a switch statement?

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



Similar Reads

Jump Statements in Java
Jumping statements are control statements that transfer execution control from one point to another point in the program. There are three Jump statements that are provided in the Java programming language: Break statement.Continue statement.Return StatementBreak statement1. Using Break Statement to exit a loop: In java, the break statement is used
5 min read
Automatic Resource Management in Java ( try with resource statements )
Java provides a feature to make the code more robust and to cut down the lines of code. This feature is known as Automatic Resource Management(ARM) using try-with-resources from Java 7 onwards. The try-with-resources statement is a try statement that declares one or more resources. This statement ensures that each resource is closed at the end of t
5 min read
Java SE 9 : Improved try-with-resources statements
In java 7 or 8 if a resource is already declared outside the try-with-resources statement, we should re-refer it with local variable. That means we have to declare a new variable in try block. Let us look at the code explaining above argument : // Java code illustrating try-with-resource import java.io.*; class Gfg { public static void main(String
2 min read
Why You Should Switch to Kotlin from Java to Develop Android Apps?
All the new Android developers see Java as the ideal option because of many reasons given it is age-old language, there are a lot of resources when it comes to java and also it's comfort levels are pretty high. But the time has come, we invite a change. The change is Kotlin. At Google I/O 2017, Google introduced Kotlin's support on Android Applicat
3 min read
Usage of Enum and Switch Keyword in Java
An Enum is a unique type of data type in java which is generally a collection (set) of constants. More specifically, a Java Enum type is a unique kind of Java class. An Enum can hold constants, methods, etc. An Enum keyword can be used with if statement, switch statement, iteration, etc. enum constants are public, static, and final by default.enum
4 min read
Three way partitioning using Dutch National Sort Algorithm(switch-case version) in Java
Given an array list arr and values lowVal and highVal. The task is to partition the array around the range such that the array List is divided into three parts. 1) All elements smaller than lowVal come first.2) All elements in range lowVal to highVVal come next.3) All elements greater than highVVal appear in the end.The individual elements of three
4 min read
Pattern Matching for Switch in Java
Pattern matching for a switch in Java is a powerful feature that was introduced in Java 14. Before this update, a switch expression could only be used to match the type of a value, rather than its actual value. However, by comparing the model, developers can now match the values ​​of Strings, enums, and records, which makes it much easier to write
8 min read
Record Patten with Switch in Java 19
In this article, we will learn how to use the Record Pattern with Switch statements in Java 19 to create more maintainable, readable code. With the Record Pattern and Switch, we can create cleaner and more efficient code, making our programming experience more productive. As we all know switch statements help to allow for pattern matching. So we ca
4 min read
Decision Making in Java (if, if-else, switch, break, continue, jump)
Decision Making in programming is similar to decision-making in real life. In programming also face some situations where we want a certain block of code to be executed when some condition is fulfilled. A programming language uses control statements to control the flow of execution of a program based on certain conditions. These are used to cause t
7 min read
String in Switch Case in Java
The switch statement is a multi-way branch statement. It provides an easy way to dispatch execution to different parts of code based on the value of the expression. Basically, the expression can be a byte, short, char, and int primitive data types. Beginning with JDK7, it also works with enumerated types ( Enums in java), the String class, and Wrap
3 min read
Library Management System Using Switch Statement in Java
Here we are supposed to design and implement a simple library management system using a switch statement in Java, where have operated the following operations Add a new book, Check Out a book, display specific book status, search specific book, and display book details using different classes. Follow the given link to build the Library Management S
9 min read
Enhancements for Switch Statement in Java 13
Java 12 improved the traditional switch statement and made it more useful. Java 13 further introduced new features. Before going into the details of new features, let's have a look at the drawbacks faced by the traditional Switch statement. Problems in Traditional Switch1. Default fall through due to missing break:The default fall-through behavior
5 min read
Writing clean if else statements
Using if else chaining some time looks more complex, this can be avoided by writing the code in small blocks. Use of conditional statement increases the code readability and much more. One best practice should be handling error case first. Below shown example shows how to handle error cases and simplify the if else logic.Examples 1: updateCache()-
5 min read
Types of Statements in JDBC
The Statement interface in JDBC is used to create SQL statements in Java and execute queries with the database. There are different types of statements used in JDBC: Create StatementPrepared StatementCallable Statement1.  Create a Statement: A Statement object is used for general-purpose access to databases and is useful for executing static SQL st
6 min read
How to Add Custom Switch using IconSwitch Library in Android?
In this article, we will learn about how to add Custom Switch to our project. As we know the Switch has only two states ON and OFF. In Custom Switch, we add icons that can be used for different purposes depending upon our requirements. With the help of this library IconSwitch, we can easily add a custom switch and it animates automatically when the
2 min read
How to Switch Themes in Android Using RadioButtons?
We have seen android app comes with two different types of mode or theme which are dark mode or light mode or we also called them as night and morning mode. In this article, we will implement the light and dark mode in android using RadioButton. What we are going to build in this article? We will be building a simple application in which we will be
4 min read
Switch in Android
Switch is a widget used in android applications for performing two-state operations such as on or off. The switch provides functionality where the user can change the settings between on and off using the switch. In this article, we will take a look at How to implement Switch in Android. A sample video is given below to get an idea about what we ar
4 min read
How to Add Switch in Android ActionBar?
In Android, Switch is a two-state toggle switch widget that is used to select a choice between two options. It is generally an on/off button that indicates the current state of the switch. Normal Basic Features for which switch can be used in ActionBar of application: To switch to the dark mode or light mode in the application.To activate or inacti
3 min read
How to Save Switch Button State in Android?
In Android, a Switch is a type of button that lets the user toggle between two actions or instances. In general, a Switch is used for selecting one between two options that can be invoking any actions or functions. In this article, we are going to see how we can save the state of the Switch Button in android. What we are going to build in this arti
3 min read
Dynamic Switch in Android
Switch is a widget used in android applications for performing two-state operations such as on or off. The switch provides functionality where the user can change the settings between on and off using the switch. In this article, we will take a look at How to Create a Switch dynamically in Android. A sample video is given below to get an idea about
7 min read
Android - Implement Night Mode using Switch
Night Mode (also known as Black Mode or Dark Mode) is a screen display that uses dark background. Opposite to Light Mode which uses light background and dark text, night mode uses a dark background and light text. Dark mode reduces battery consumption, this is because the device finds it easier to run the dark background as it does not have to ligh
2 min read
Difference Between java.sql.Time, java.sql.Timestamp and java.sql.Date in Java
Across the software projects, we are using java.sql.Time, java.sql.Timestamp and java.sql.Date in many instances. Whenever the java application interacts with the database, we should use these instead of java.util.Date. The reason is JDBC i.e. java database connectivity uses these to identify SQL Date and Timestamp. Here let us see the differences
7 min read
Java AWT vs Java Swing vs Java FX
Java's UI frameworks include Java AWT, Java Swing, and JavaFX. This plays a very important role in creating the user experience of Java applications. These frameworks provide a range of tools and components for creating graphical user interfaces (GUIs) that are not only functional but also visually appealing. As a Java developer, selecting the righ
11 min read
Java.io.ObjectInputStream Class in Java | Set 2
Java.io.ObjectInputStream Class in Java | Set 1 Note : Java codes mentioned in this article won't run on Online IDE as the file used in the code doesn't exists online. So, to verify the working of the codes, you can copy them to your System and can run it over there. More Methods of ObjectInputStream Class : defaultReadObject() : java.io.ObjectInpu
6 min read
Java.lang.Class class in Java | Set 1
Java provides a class with name Class in java.lang package. Instances of the class Class represent classes and interfaces in a running Java application. The primitive Java types (boolean, byte, char, short, int, long, float, and double), and the keyword void are also represented as Class objects. It has no public constructor. Class objects are cons
15+ min read
Java.lang.StrictMath class in Java | Set 2
Java.lang.StrictMath Class in Java | Set 1More methods of java.lang.StrictMath class 13. exp() : java.lang.StrictMath.exp(double arg) method returns the Euler’s number raised to the power of double argument. Important cases: Result is NaN, if argument is NaN.Result is +ve infinity, if the argument is +ve infinity.Result is +ve zero, if argument is
6 min read
java.lang.instrument.ClassDefinition Class in Java
This class is used to bind together the supplied class and class file bytes in a single ClassDefinition object. These class provide methods to extract information about the type of class and class file bytes of an object. This class is a subclass of java.lang.Object class. Class declaration: public final class ClassDefinition extends ObjectConstruc
2 min read
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap also contains functions that support retrieval and deletion at both, high and low end of values and hence give a lot of flexibility in applicability and daily use. This function is poll() and has 2 variants discussed in this article. 1. pollFirstEntry() : It removes and retrieves a key-value pair with the least key value in the ma
4 min read
Java.util.TreeMap.floorEntry() and floorKey() in Java
Finding greatest number less than given value is used in many a places and having that feature in a map based container is always a plus. Java.util.TreeMap also offers this functionality using floor() function. There are 2 variants, both are discussed below. 1. floorEntry() : It returns a key-value mapping associated with the greatest key less than
3 min read
java.lang.Math.atan2() in Java
atan2() is an inbuilt method in Java that is used to return the theta component from the polar coordinate. The atan2() method returns a numeric value between -[Tex]\pi [/Tex]and [Tex]\pi [/Tex]representing the angle [Tex]\theta [/Tex]of a (x, y) point and the positive x-axis. It is the counterclockwise angle, measured in radian, between the positiv
1 min read
Article Tags :
Practice Tags :