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 in Java

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.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

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.

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.

Learn From The Best Mentors in the Industry!

Automation Testing Masters ProgramExplore Program
Learn From The Best Mentors in the Industry!

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

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

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

  • 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

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!
  • 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

Don't miss out on the opportunity to become a Certified Professional with Simplilearn's Post Graduate Program in Full Stack Web Development. Enroll Today!

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. Check Simplilearn's Post Graduate Program in Full Stack Web Development. This course can help you gain the right skills and make you job-ready.

If you have any questions, feel free to post them in the comments section below. Our team will get back to you at the earliest.

Our Software Development Courses Duration And Fees

Software Development Course typically range from a few weeks to several months, with fees varying based on program and institution.

Program NameDurationFees
Caltech Coding Bootcamp

Cohort Starts: 17 Jun, 2024

6 Months$ 8,000
Full Stack Developer - MERN Stack

Cohort Starts: 30 Apr, 2024

6 Months$ 1,449
Automation Test Engineer

Cohort Starts: 1 May, 2024

11 Months$ 1,499
Full Stack Java Developer

Cohort Starts: 14 May, 2024

6 Months$ 1,449