Open In App

Switch Statements in Java

Last Updated : 09 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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

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

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

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

  1. There can be any number of cases just imposing condition check but remember duplicate case/s values are not allowed.
  2. The value for a case must be of the same data type as the variable in the switch.
  3. The value for a case must be constant or literal. Variables are not allowed.
  4. The break statement is used inside the switch to terminate a statement sequence.
  5. The break statement is optional. If omitted, execution will continue on into the next case.
  6. The default statement is optional and can appear anywhere inside the switch block. In case, if it is not at the end, then a break statement must be kept after the default statement to omit the execution of the next case statement.
Note: Until Java-6, switch case argument cannot be of String type but Java 7 onward we can use String type argument in Switch Case.

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

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

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

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

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

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

Example:

Writing default in the middle of switch statements:

Java
/*package whatever //do not write package name here */

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 in starting 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 label and switch arguments can be a constant expression. The switch argument can be a variable expression.

Example:

Using variable switch arguement.

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

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 provides four wrapper classes to use: Integer, Short, Byte, and Long in switch statements.

Example:

Java Wrapper in switch case.

Java
public class WrapperSwitchExample {

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

        switch (age.intValue()) { // 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: In this code we will identify the weekday through (1-7) numbers.

Java
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a day number (1-7): ");
        int day = scanner.nextInt();

        switch (day) {
            default:
                System.out.println("Not a valid weekday.");
                break;
            case 1:
                System.out.println("It's Monday!");
                break;
            case 2:
                System.out.println("It's Tuesday!");
                break;
            case 3:
                System.out.println("It's Wednesday!");
                break;
            case 4:
                System.out.println("It's Thursday!");
                break;
            case 5:
                System.out.println("It's Friday!");
                break;
            case 6:
                System.out.println("It's Saturday!");
                break;
            case 7:
                System.out.println("It's Sunday!");
                break;
        }
    }
}

Output

Enter a day number (1-7): 8
Not a valid weekday.


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 certain block of code based on the value of a single expression. They can be considered as an alternative to if-else-if statements in programming.

Java Switch Statements- FAQs

How to use switch statements in Java

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

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

Can we pass null to a switch

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

Can you return to a switch statement

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



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads