What is a Switch Case in Java & How to Use It?

By Pavan Vadapalli

Updated on Aug 22, 2025 | 8 min read | 6.94K+ views

Share:

Imagine a vending machine. You press a specific code (a "case"), and it gives you a specific item. You don't have to check every single item one by one; you go directly to your choice. This is exactly what the switch case in Java does for your code. 

Instead of writing a long and messy chain of if-else if statements, the switch statement provides a clean and efficient way to execute different blocks of code based on a specific value.  

This guide will be your complete tutorial on how to use switch case in Java, breaking down the syntax with clear examples so you can start writing more organized code today. 

Improve your understanding of switch case in java with our online software engineering courses. Learn how to apply switch case in java, where to use across different industry applications!  

 

What is a switch case in Java?

Java supports three kinds of statements: expression statements for changing values of variables, calling methods and creating objects, declaration statements for declaring variables, and control-flow statements for determining the order of execution of statements.

If you're looking to master core Java concepts like the switch statement and build a strong foundation in programming, here are some top-rated courses from upGrad to help you get there: 

The Java switch case statement is a type of control-flow statement that allows the value of an expression or variable to change the control flow of program execution through a multi-way branch. In contrast to if-then and if-then-else statements, the Java switch statement has several execution paths. Switch case in Java works with short, byte, int, and char primitive data types. From JDK7, Java switch can also be used with String class, enumerated types, and Wrapper classes that wrap primitive data types such as Byte, Character, Integer, and Short.

The body of a switch case statement in Java is called a switch block. Every statement in the switch block is labelled using one or more cases or default labels. Hence, the switch statement evaluates its expression, followed by the execution of all the statements which follow the matching case label.

Given below is the syntax of the switch case statement:

// switch statement 

switch(expression)

{

   // case statements

   // values must be of same type of expression

   case value1 :

      // Statements

      break; // break is optional

   

   case value2 :

      // Statements

      break; // break is optional

   

   // We can have any number of case statements

   // below is default statement, used when none of the cases is true. 

   // No break is needed in the default case.

   default : 

      // Statements

}

Check out upGrad’s AI-Driven Full-Stack Development Bootcamp 

Example of the Java switch statement

The following Java code example declares an int named “month” whose value represents one of the 12 months of the year. The code uses the switch case statement to display the month’s name based on the month’s value.

public class SwitchExample {

    public static void main(String[] args) {

        int month = 6;

        String monthString;

        switch (month) {

            case 1:  monthString = “January”;

                     break;

            case 2:  monthString = “February”;

                     break;

            case 3:  monthString = “March”;

                     break;

            case 4:  monthString = “April”;

                     break;

            case 5:  monthString = “May”;

                     break;

            case 6:  monthString = “June”;

                     break;

            case 7:  monthString = “July”;

                     break;

            case 8:  monthString = “August”;

                     break;

            case 9:  monthString = “September”;

                     break;

            case 10: monthString = “October”;

                     break;

            case 11: monthString = “November”;

                     break;

            case 12: monthString = “December”;

                     break;

            default: monthString = “Invalid month”;

                     break;

        }

        System.out.println(monthString);

    }

}

Output: 
June

Software Development Courses to upskill

Explore Software Development Courses for Career Progression

Coverage of AWS, Microsoft Azure and GCP services

Certification8 Months

Job-Linked Program

Bootcamp36 Weeks

Purpose of break statement in Java switch case 

The break statement is an essential aspect of the Java switch case that terminates the enclosing switch statement. The break statement is required because without it, statements in the switch block would fall through. Thus, regardless of the expression of the succeeding case labels, all statements after the matching case label are sequentially executed until a break statement is encountered. 

The following code is an example to show a switch block falling through in the absence of the break statement.

public class SwitchExampleFallThrough {

    public static void main(String[] args) {

        java.util.ArrayList<String> futureMonths =

            new java.util.ArrayList<String>();

        int month = 6;

        switch (month) {

            case 1:  futureMonths.add(“January”);

            case 2:  futureMonths.add(“February”);

            case 3:  futureMonths.add(“March”);

            case 4:  futureMonths.add(“April”);

            case 5:  futureMonths.add(“May”);

            case 6:  futureMonths.add(“June”);

            case 7:  futureMonths.add(“July”);

            case 8:  futureMonths.add(“August”);

            case 9:  futureMonths.add(“September”);

            case 10: futureMonths.add(“October”);

            case 11: futureMonths.add(“November”);

            case 12: futureMonths.add(“December”);

                     break;

            default: break;

        }

        if (futureMonths.isEmpty()) {

            System.out.println(“Invalid month number”);

        } else {

            for (String monthName : futureMonths) {

               System.out.println(monthName);

            }

        }

    }

}

Output:
June

July

August

September

October

November

December

The above code displays the month of the year corresponding to the integer month and the months that follow. Here, the final break statement serves no purpose because the flow falls out of the switch statement. The use of the break statement is helpful because it makes the code less error-prone and modifications easier. The default section in the code handles all values not regulated by any of the case sections.

Java switch statement with multiple case labels

Switch statements in Java can have multiple case labels as well. The following code illustrates the same – here, the number of days in a particular month of the year is calculated.

class SwitchMultiple{

    public static void main(String[] args) {

        int month = 2;

        int year = 2020;

        int numDays = 0;

        switch (month) {

            case 1: case 3: case 5:

            case 7: case 8: case 10:

            case 12:

                numDays = 31;

                break;

            case 4: case 6:

            case 9: case 11:

                numDays = 30;

                break;

            case 2:

                if (((year % 4 == 0) && 

                     !(year % 100 == 0))

                     || (year % 400 == 0))

                    numDays = 29;

                else

                    numDays = 28;

                break;

            default:

                System.out.println(“Invalid month.”);

                break;

        }

        System.out.println(“Number of Days = “

                           + numDays);

    }

}

Output:
Number of Days = 29

Learn Online software development courses from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs, or Masters Programs to fast-track your career.

Nested Java switch case statements

A nested switch is when you use a switch as a part of the sequence of statements of an outer switch. In this case, there is no conflict between the case constants in the other switch and those in the inner switch because a switch statement defines its own block.

The following example demonstrates the use of nested Java switch-case statements:

public class TestNest {

public static void main(String[] args)

{

String Branch = “CSE”;

int year = 2;

switch (year) {

case 1:

System.out.println(“Elective courses : Algebra, Advance English”);

break;

case 2:

switch (Branch) // nested switch

{

case “CSE”:

case “CCE”:

System.out.println(“Elective courses : Big Data, Machine Learning”);

break;

case “ECE”:

System.out.println(“elective courses : Antenna Engineering”);

break;

default:

System.out.println(“Elective courses : Optimization”);

}

}

}

}

Output:
Elective courses: Big Data, Machine Learning

Use of strings in switch statements 

Beginning from JDK7, you can use a String object in the expression of a switch statement. The comparison of the string object in the switch statement’s expression with associated expressions of each case label is as if it was using the String.equals method. Also, the comparison of string objects in the switch statement expression is case-sensitive.

The following code example displays the type of game based on the value of the String named “game.” 

public class StringInSwitchStatementExample {  

    public static void main(String[] args) {  

        String game = “Cricket”;  

        switch(game){  

        case “Volleyball”: case”Football”: case”Cricket”:  

            System.out.println(“This is an outdoor game”);  

            break;  

        case”Card Games”: case”Chess”: case”Puzzles”: case”Indoor basketball”:  

            System.out.println(“This is an indoor game”);  

            break;  

        default:   

            System.out.println(“What game it is?”);  

        }  

    }  

}  

Output:
This is an outdoor game

Rules to remember when using Java switch statements

It would be best if you keep certain rules in mind while using Java switch statements. Following is a list of the same:

  • The value for a case and the variable in the switch should have the same data type.
  • Java switch statements do not allow duplicate case values.
  • A case value should be literal or a constant. Variables are not allowed.
  • The use of the break statement inside the switch terminates a statement sequence.
  • The break statement is optional and omitting it will continue execution into the subsequent case.
  • The default statement is also optional and can occur anywhere within the switch block. If it is not placed at the end, a break statement must be added after the default statement to skip the execution of the succeeding case statement. 

Subscribe to upGrad's Newsletter

Join thousands of learners who receive useful tips

Promise we won't spam!

Conclusion 

The switch case in Java is a powerful and elegant tool for managing complex conditional logic. It provides a cleaner, more readable alternative to long if-else if chains, making your code easier to maintain and debug. 

This guide has shown you how to use switch case in Java effectively, from its basic syntax to modern enhancements like arrow cases and expressions. By mastering this fundamental control flow statement, you are taking a significant step toward writing more professional and efficient Java code. Keep practicing, and you'll find it an indispensable part of your programming toolkit. 

Way Forward

Java has unmatched popularity among programmers and developers and is one of the most in-demand programming languages today. Needless to say, budding developers and software engineers who want to upskill themselves for the ever-evolving job market need to get a stronghold over their Java skills.

If you want to kickstart your journey towards a promising career in software engineering, upGrad’s software development courses can make it possbile. 

Here are some additional courses that can boost your programming journey and prepare you for real-world development: 

Boost your career with our popular Software Engineering courses, offering hands-on training and expert guidance to turn you into a skilled software developer.

Master in-demand Software Development skills like coding, system design, DevOps, and agile methodologies to excel in today’s competitive tech industry.

Stay informed with our widely-read Software Development articles, covering everything from coding techniques to the latest advancements in software engineering.

Frequently Asked Questions (FAQs)

1. What is a case in a switch statement?

In a switch case in Java, the case keyword is used to define a specific value to compare against the variable in the switch expression. Think of each case as a potential match or a labeled branch of code. When the switch statement executes, it evaluates its expression and then looks for a case label whose value is equal to the result. If a match is found, the code block following that case label is executed. 

2. What is the difference between switch case and if-else?

The primary difference lies in how they evaluate conditions. An if-else statement is highly flexible and can evaluate complex boolean expressions (e.g., if (x > 10 && y < 20)). A traditional switch case in Java is more limited; it can only check for equality against a list of discrete constant values. While if-else is a general-purpose tool for any conditional logic, a switch is a specialized tool that provides a cleaner and more readable way to handle a multi-branch choice based on a single variable's value. 

3. What are the advantages of a switch case?

The main advantage of using a switch case in Java over a long chain of if-else if statements is code readability and maintainability. A switch block clearly organizes the code into distinct cases, making it easier to see all possible paths at a glance. In some older versions of Java, the compiler could also optimize a switch statement using a "jump table," which could make it slightly faster than a sequence of if-else checks, although this performance difference is less significant in modern JVMs. 

4. What is the role of the break statement in a switch case?

The break statement is crucial for controlling the flow of execution inside a switch block. When a matching case is found, its code is executed. If the Java interpreter then encounters a break statement, it immediately exits the entire switch block and continues with the code that follows it. Without a break, the program would continue executing the code in all the subsequent case blocks until it either hits a break or reaches the end of the switch statement. 

5. What is "fall-through" in a Java switch case?

"Fall-through" is the term for what happens when you intentionally omit the break statement in a case block. This causes the execution to "fall through" and continue running the code in the next case block, regardless of whether its value matches. This can be a useful feature for grouping cases that need to share some code, but it is also a common source of bugs if a break is forgotten accidentally. A clear understanding of this is essential to know how to use switch case in Java correctly. 

6. What is the purpose of the default case?

The default case in a switch case in Java acts as a catch-all option. It is executed if the value of the switch expression does not match any of the other case labels. It is similar to the final else in an if-else if chain. While it is not mandatory, it is a very good practice to include a default case to handle unexpected values gracefully and prevent your program from doing nothing if no match is found. 

7. Does the default case need a break statement?

If the default case is the last block in the switch statement, it does not technically need a break because the execution will naturally exit the switch block right after it finishes. However, it is widely considered a good coding practice to include a break anyway. This prevents accidental fall-through errors if another case is added after the default case in the future. 

8. What data types can be used in a switch statement in Java?

In traditional Java, the switch statement was limited to primitive data types like byte, short, char, and int, their wrapper classes, and enum types. Starting with Java 7, support for the String class was added. Modern versions of Java have further enhanced the switch case in Java, allowing it to be used with a wider range of types, especially in its expression form. 

9. Can I use long, float, or double in a switch case?

No, you cannot use long, float, double, or boolean in a traditional switch statement's expression. This is because the design of the switch statement was optimized for exact value matching using integer-based comparisons, and floating-point numbers can have precision issues that make exact equality checks unreliable. 

10. Can a case have multiple values in Java?

In modern versions of Java (starting with Java 14), you can specify multiple values for a single case label, separated by commas. This provides a much cleaner way to handle situations where several different values should execute the same block of code, avoiding the need for the traditional "fall-through" technique. This is a significant improvement in how to use switch case in Java.

Java

// Modern Java (14+) 
switch (day) { 
   case MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY -> System.out.println("Weekday"); 
   case SATURDAY, SUNDAY -> System.out.println("Weekend"); 

11. What are "arrow cases" or "switch expressions" in modern Java?

Switch expressions, introduced as a standard feature in Java 14, provide a more concise and powerful syntax for switch. Instead of the traditional colon (:) and break, you can use an arrow (->) to separate the case label from the code to be executed. This syntax does not have "fall-through" behavior, which eliminates a common source of bugs. A switch expression can also return a value, allowing you to use it directly in an assignment. 

12. What happens if I use a variable in a case label?

You cannot use a variable in a case label. The values for each case in a switch case in Java must be compile-time constants. This means they must be a literal value (like 5 or "hello") or a final variable that was initialized with a literal. This restriction allows the Java compiler to optimize the switch statement for better performance. 

13. Can I nest a switch statement inside another switch statement?

Yes, you can nest a switch statement inside another one, just as you can nest if statements. However, this can make the code very complex and difficult to read and maintain. If you find yourself needing to nest switch statements, it might be a sign that your logic is too complicated and could be a good opportunity to refactor your code, perhaps by breaking it down into smaller, separate methods. 

14. What is the difference between a switch statement and a switch expression?

A switch statement is a traditional control flow statement that directs the program's execution to a specific block of code. It does not return a value. A switch expression, introduced in modern Java, is an expression that evaluates to a single value. This means you can use it on the right side of an assignment statement (e.g., String result = switch(day) { ... };). Switch expressions are also exhaustive, meaning you must cover all possible values, which helps prevent bugs. 

15. What are some best practices for using a switch case?

Some best practices for how to use switch case in Java include always including a default case to handle unexpected values, using a break statement at the end of every case to prevent accidental fall-through (unless fall-through is intended and commented), and keeping the code within each case block short and simple. If a case requires a lot of logic, it's better to call a separate method. 

16. When is it better to use an if-else if statement instead of a switch?

An if-else if statement is a better choice when you need to evaluate complex conditions that go beyond simple equality checks. For example, if you need to check a range of values (if (age > 18 && age < 65)), test against multiple variables, or evaluate the result of a method call, an if-else if chain provides the necessary flexibility that a traditional switch cannot. 

17. Can enum types be used in a switch case?

Yes, using enum types in a switch case in Java is a very common and highly recommended practice. It makes the code much more readable and type-safe because you are switching on a well-defined set of constants rather than arbitrary integers or strings. When you use an enum in a switch, the compiler can also warn you if you have not covered all the possible enum values in your case labels. 

18. How can I improve my understanding of Java's control flow statements?

The best way to improve is through a combination of structured learning and hands-on practice. A comprehensive program, like the Java development courses offered by upGrad, can provide a strong foundation by teaching you the theory and best practices. You should also practice by solving coding challenges and building small projects that require you to implement different conditional logic, which will help you master concepts like the switch case in Java. 

19. What does the "colon (:)" and "arrow (->)" syntax signify in a switch?

In a switch case in Java, the syntax you use determines the behavior. The traditional colon (:) syntax requires you to use a break statement to prevent fall-through. The modern arrow (->) syntax, used in switch expressions and enhanced switch statements, does not have fall-through behavior. If a case with an arrow matches, only the code to the right of the arrow is executed, and the switch block is automatically exited. 

20. What is the main purpose of a switch statement in programming?

The main purpose of a switch case in Java is to provide a clean, readable, and efficient way to control the flow of a program based on the value of a single variable or expression. It is a specialized selection control statement that simplifies the implementation of multi-way branching, where you need to choose one of several different paths of execution. Understanding how to use switch case in Java effectively is a key skill for writing organized and maintainable code.

Pavan Vadapalli

900 articles published

Pavan Vadapalli is the Director of Engineering , bringing over 18 years of experience in software engineering, technology leadership, and startup innovation. Holding a B.Tech and an MBA from the India...

Get Free Consultation

+91

By submitting, I accept the T&C and
Privacy Policy

India’s #1 Tech University

Executive PG Certification in AI-Powered Full Stack Development

77%

seats filled

View Program

Top Resources

Recommended Programs

upGrad

upGrad

AI-Driven Full-Stack Development

Job-Linked Program

Bootcamp

36 Weeks

upGrad

upGrad KnowledgeHut

Professional Certificate Program in UI/UX Design & Design Thinking

#1 Course for UI/UX Designers

Bootcamp

3 Months

IIIT Bangalore logo
new course

Executive PG Certification

9.5 Months