Switch Case in Java

The switch statement or switch case in java is a multi-way branch statement. Based on the value of the expression given, different parts of code can be executed quickly. The given expression can be of a primitive data type such as int, char, short, byte, and char. With JDK7, the switch case in java works with the string and wrapper class and enumerated data type (enum in java).

Use of Switch Case

The switch case in java is used to select one of many code blocks for execution.

Break keyword: As java reaches a break keyword, the control breaks out of the switch block. The execution of code stops on encountering this keyword, and the case testing inside the block ends as the match is found. A lot of execution time can be saved because it ignores the rest of the code's execution when there is a break.

Default keyword: The keyword is used to specify the code executed when the expression does not match any test case.

How Does the Switch Statement Work

This is how switch case in Java work:

The switch case in Java works like an if-else ladder, i.e., multiple conditions can be checked at once. Switch is provided with an expression that can be a constant or literal expression that can be evaluated. The value of the expression is matched with each test case till a match is found. If there is no match, the default keyword, if specified- the associated code executes. Otherwise, the code specified for the matched test case is executed.

Full Stack Java Developer Course

The Gateway to Master Web DevelopmentExplore Course
Full Stack Java Developer Course

There are some things to be remembered while using switch case in java:

  • Two cases cannot have the same value
  • The data type of variable in the switch needs to be the same as all test cases' values.
  • The value for the cases needs to be literal or constant but not a variable. For example:

Valid expressions: switch (1+2+3+4) , switch(1*2+3%4)

Invalid expressions: switch(ef+gh), switch(e+f+g)

  • The break statement is used to terminate the statement sequence inside the switch.
  • The test case values need not be in order (ascending or descending). It can occur as per requirement.
  • If the break statement is omitted, the execution will continue into the next test case.
  • The default statement can appear anywhere inside the switch block, but a break statement should follow it if the default is not in the end.
  • Nesting is allowed, but it makes the program more complex.

For example, the code below uses the monthly number to calculate the month name:

public class Main {

  public static void main(String[] args) {

int month = 4;

    switch (month) {

      case 1:

        System.out.println("January");

        break;

      case 2:

        System.out.println("February");

        break;

      case 3:

        System.out.println("March");

        break;

      case 4:

        System.out.println("April");

        break;

      case 5:

        System.out.println("May");

        break;

      case 6:

        System.out.println("June");

        break;

     default: System.out.println("In next half");

}

  }

}

Output:

SwitchStatement.

Syntax of Switch Case in Java[1] 

The syntax of the switch statement is as follows:

switch(expression)

{

   // The switch block has case statements whose values must be of the same type of expression

   case value1 :

   // Code statement to be executed

   break; // break is optional

   case value2 :

   // Code statement to be executed

   break; // break is optional

   // There can be several case statements

   // When none of the cases is true, a default statement is used, and no break is needed in the default case.

   default :

   // Code statement to be executed

}

Execution while Omitting the Break Statement

Since the break statement is optional, we can omit it. On execution without a break statement, control will continue into the next case. There can be multiple cases without a break statement between them as it is desirable in some cases, such as the given one. This code displays whether a month has 30, 31, or 28 days:

Java program to demonstrate switch case with multiple cases without break statements.

public class Main {

  public static void main(String[] args) {

int month = 4;

    switch (month) {

      case 1:   

      case 3:  

      case 5:

      case 7:

      case 8:

      case 10:

      case 12:

        System.out.println("31 days");

        break;

     case 2:  System.out.println("28 days");

        break;

     case 4:

     case 6:

     case 9:

     case 11:

     System.out.println("30 days");

        break;

     default: System.out.println("Error");

}

  }

}

Output:

OmittingtheBreakStatement

More examples:

  • Nested Switch Case in Java

A switch case can be used as a part of an outer switch's statement sequence. This is known as a nested switch case in java. As a switch case defines its block, the case constraints in the inner switch do not conflict with those in the outer switch. Here is a Java program to demonstrate nested switch case statement:

public class Main { 

public static void main(String[] args) 

String Branch = "CS"; 

int year = 1; 

switch (year) { 

case 1: 

System.out.println("elective courses : Advance Maths, Algebra"); 

break; 

case 2: 

switch (Branch)  

case "CS": 

case "ECE": 

System.out.println("elective courses : ML, Big Data"); 

break; 

case "IT": 

System.out.println("elective courses : Software Engineering"); 

break; 

default: 

System.out.println("Elective courses : English"); 

}

Output:

NestedSwitchCase

FREE Java Certification Training

Learn A-Z of Java like never beforeEnroll Now
FREE Java Certification Training

  • Java Program to Demonstrate the Use of Enum in Switch Statement  

Code:

public class Main {      

      public enum Day {  S, M, T, W, Th, F, St  }    

      public static void main(String args[])    

      {    

        Day[] DayNow = Day.values();    

          for (Day Now : DayNow)    

          {    

                switch (Now)    

                {    

                    case S:    

                        System.out.println("Sunday");    

                        break;    

                    case M:    

                        System.out.println("Monday");    

                        break;    

                    case T:    

                        System.out.println("Tuesday");    

                        break;         

                    case W:    

                        System.out.println("Wednesday");    

                        break;    

                    case Th:    

                        System.out.println("Thursday");    

                        break;    

                    case F:    

                        System.out.println("Friday");    

                        break;    

                    case St:    

                        System.out.println("Saturday");    

                        break;    

                }    

            }    

        }    

}    

Output:

EnuminSwitchStatement%20

  • Java Program to Demonstrate the Use of Wrapper class in Switch Statement  

Code:

public class Main {       

      public static void main(String args[])  

      {         

            Integer age = 18;        

            switch (age)  

            {  

                case (16):            

                    System.out.println("You are not an adult.");  

                    break;  

                case (18):                

                    System.out.println("You are an adult.");  

                    break;  

                case (65):                

                    System.out.println("You are senior citizen.");  

                    break;  

                default:  

                    System.out.println("Please give the valid age.");  

                    break;  

            }             

        }  

}  

Output:

WrapperclassinSwitchState

Get a firm foundation in Java, the most commonly used programming language in software development with the Java Certification Training Course.

Conclusion 

The switch case in java executes one statement from multiple ones. Thus, it is like an if-else-if ladder statement. It works with a lot of data types. The switch statement is used to test the equality of a variable against several values specified in the test cases. 

Java is one of the most widely used programming languages used today. And if you wish to make a career out of it, mastering it is definitely the first step. Enrol in Simplilearn’s Java Certification Training Program today, and master Java now!

About the Author

SimplilearnSimplilearn

Simplilearn is one of the world’s leading providers of online training for Digital Marketing, Cloud Computing, Project Management, Data Science, IT, Software Development, and many other emerging technologies.

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.