Explore Courses
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Birla Institute of Management Technology Birla Institute of Management Technology Post Graduate Diploma in Management (BIMTECH)
  • 24 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Popular
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science & AI (Executive)
  • 12 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
University of MarylandIIIT BangalorePost Graduate Certificate in Data Science & AI (Executive)
  • 8-8.5 Months
upGradupGradData Science Bootcamp with AI
  • 6 months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
OP Jindal Global UniversityOP Jindal Global UniversityMaster of Design in User Experience Design
  • 12 Months
Popular
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Rushford, GenevaRushford Business SchoolDBA Doctorate in Technology (Computer Science)
  • 36 Months
IIIT BangaloreIIIT BangaloreCloud Computing and DevOps Program (Executive)
  • 8 Months
New
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Popular
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
Golden Gate University Golden Gate University Doctor of Business Administration in Digital Leadership
  • 36 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
Popular
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
Bestseller
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
IIIT BangaloreIIIT BangalorePost Graduate Certificate in Machine Learning & Deep Learning (Executive)
  • 8 Months
Bestseller
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in AI and Emerging Technologies (Blended Learning Program)
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
ESGCI, ParisESGCI, ParisDoctorate of Business Administration (DBA) from ESGCI, Paris
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration From Golden Gate University, San Francisco
  • 36 Months
Rushford Business SchoolRushford Business SchoolDoctor of Business Administration from Rushford Business School, Switzerland)
  • 36 Months
Edgewood CollegeEdgewood CollegeDoctorate of Business Administration from Edgewood College
  • 24 Months
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with Concentration in Generative AI
  • 36 Months
Golden Gate University Golden Gate University DBA in Digital Leadership from Golden Gate University, San Francisco
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Deakin Business School and Institute of Management Technology, GhaziabadDeakin Business School and IMT, GhaziabadMBA (Master of Business Administration)
  • 12 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science (Executive)
  • 12 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityO.P.Jindal Global University
  • 12 Months
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (AI/ML)
  • 36 Months
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDBA Specialisation in AI & ML
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
New
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGrad KnowledgeHutupGrad KnowledgeHutAzure Administrator Certification (AZ-104)
  • 24 Hours
KnowledgeHut upGradKnowledgeHut upGradAWS Cloud Practioner Essentials Certification
  • 1 Week
KnowledgeHut upGradKnowledgeHut upGradAzure Data Engineering Training (DP-203)
  • 1 Week
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
Loyola Institute of Business Administration (LIBA)Loyola Institute of Business Administration (LIBA)Executive PG Programme in Human Resource Management
  • 11 Months
Popular
Goa Institute of ManagementGoa Institute of ManagementExecutive PG Program in Healthcare Management
  • 11 Months
IMT GhaziabadIMT GhaziabadAdvanced General Management Program
  • 11 Months
Golden Gate UniversityGolden Gate UniversityProfessional Certificate in Global Business Management
  • 6-8 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
IU, GermanyIU, GermanyMaster of Business Administration (90 ECTS)
  • 18 Months
Bestseller
IU, GermanyIU, GermanyMaster in International Management (120 ECTS)
  • 24 Months
Popular
IU, GermanyIU, GermanyB.Sc. Computer Science (180 ECTS)
  • 36 Months
Clark UniversityClark UniversityMaster of Business Administration
  • 23 Months
New
Golden Gate UniversityGolden Gate UniversityMaster of Business Administration
  • 20 Months
Clark University, USClark University, USMS in Project Management
  • 20 Months
New
Edgewood CollegeEdgewood CollegeMaster of Business Administration
  • 23 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 5 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
upGradupGradUI/UX Bootcamp
  • 3 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
upGradupGradDigital Marketing Accelerator Program
  • 05 Months

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

Updated on 14 November, 2022

6.23K+ views
8 min read

The switch case in Java is one of the many Java statements that tell the programming language what to do. Like sentences in the English language that gives a complete idea of the text and include clauses, Java statements are commands including one or more expressions that the Java interpreter executes. In simpler terms, a Java statement is an instruction explaining what should happen. 

A Java statement ends in a semicolon (;) and tells Java to process instructions up to that semicolon. By default, the Java interpreter follows the order in which statements are written and runs one statement after another. However, statements that control the program flow (flow-control statements), such as loops and conditionals, do not follow the default order of execution. This article focuses on one such type of selection control mechanism – the Java switch case statement.

Check out our free courses to get an edge over the competition  

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.

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.

Check out upGrad’s Advanced Certification in DevOps

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 Full Stack Development Bootcamp (JS/MERN) 

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

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. 

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.

upGrad’s Job-linked PG Certification in Software Engineering is specially designed for freshers and final year candidates who want to learn to code and get placed into entry-level software roles. 

If you are wondering what the 5-month online course entails, here are some highlights to give you an idea:

  • Earn MERN Stack and Cloud-Native Specializations
  • Learn top skills like Java, DSA, CSS3, HTML5, AWS, MERN, SQL and NoSQL databases, and more
  • 500+ hours of content with 350+ hours of hands-on training
  • Five industry projects and 50+ live sessions
  • Placement preparation and career guidance
  • Discussion forums and strong peer network

If you want to kickstart your journey towards a promising career in software engineering, here’s your chance to learn from the best.

Frequently Asked Questions (FAQs)

1. What is a case in a switch statement?

A switch statement in Java allows the testing of a variable’s equality against a list of values. Here, each value is known as a case, and the variable switched on is checked for each of the cases.

2. What are the advantages of a switch case?

The primary advantage of Java switch case statements over traditional if-else cascades is that the former allows programmers to write a more compact, clear, and readable code. On the other hand, if-else statements often involve a lot of code repetitions. Thus, if we want to change a specific part of the code, we would have to make changes in other places. To avoid this time-consuming and error-prone process, it is wiser to use switch cases.

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

In the case of switch statements, cases are executed sequentially one after the other until the break keyword is encountered or the default statement is executed. On the contrary, in the case of if-else statements, either the ‘if’ or ‘else’ block gets executed depending on the condition.

RELATED PROGRAMS