Introduction

The conditions and logical statements are an integral part of any program. A code is mainly comprised of series of conditions and their possible outputs in either case. A Switch case statement is one of the conditional statements commonly found in almost every other programming language.

Switch case in Java

The switch case is very commonly used in Java. It is a multi-way branch statement that provides paths to execute different parts of the code based on the value of the expression. The expression can be a byte, short, char, and int primitive data types. From JDK7, it can also be used with enumerated (Enum) data types in Java, the String class and Wrapper classes.

Following is the Syntax of switch case in Java: 

switch(variable or an integer expression)

{

   // case statements

 case value 1 :

      // Statements to executed in case of value 1 is true

   break; // optional

   case value 2 :

      // Statements to executed in case of value 2 is true

   break; // optional

   // Any number of case statements can be added to the code

   // An optional default statement is written at the end.

   default :

      // Statements to executed when none of the cases is true

      break; // optional here as well }

Despite being optional, the break statement is mostly used with switch case in Java.

Below is the code snippet demonstrating a simple switch case in Java:

public class SwitchCase_Example1 {

   public static void main(String args[]){

     int num = 10;

     switch(num * 5 + num)

     {

        case 20:

           System.out.println("Option 1: The Value is: "+num);

         case 40:

           System.out.println("Option 2: The Value is: "+num);

         case 60:

           System.out.println("Option 3: The Value is: "+num);

        default:

           System.out.println("Default Case: The Value is: "+num);

      }

   }

}

Output:

Option 3: Value is 60

In the above switch case, the switch expression is “num* 5 + num” where num is 10 and the expression will turn out to be 10 * 5 + 10 which solve to be 60, you can also give a variable in place of expression. Since the third case is defined with a value of 60, it got executed. Although the default case is optional in switch case Java but in case there is no case defined with the value 60, then the default case will be executed.

Default case makes the code more understandable for the user as instead of a black screen, the statement in the default case would make more sense in case of no case matches the expression.

Break statement in switch case in Java

The break statement is optional and is not needed to be used in all conditions. Having said that, there are certain scenarios where it becomes crucial to use break statements to achieve the logically accurate output. Before we further discuss the break statement, see this Java switch case example where break statement has not been used:

public class SwitchCase_Example2a {

   public static void main(String[] args) {

    int day = 4;

    switch (day) {

      case 1:

        System.out.println("Monday");

      case 2:

        System.out.println("Tuesday");

      case 3:

        System.out.println("Wednesday");

      case 4:

        System.out.println("Thursday");

      case 5:

        System.out.println("Friday");

      case 6:

        System.out.println("Saturday");

      case 7:

        System.out.println("Sunday");

      default:

         System.out.println("Incorrect Number");

    }

  }

}

Output:

Thursday

Friday

Saturday

Sunday

In the above code, we have passed integer value 4 to the switch, which should execute case 4, however, we do not have a break statement after case 4 that caused the flow to pass to the subsequent cases till the end. In return, we got all the days printed after Thursday. The solution to this problem is using a break statement.

Break statements are used to control the program flow. It directs the program flow to come out of the switch body. Whenever a break statement is encountered in any switch case, the execution flow directly comes out of the case after executing it, ignoring all the other cases.

Now, see the same Java switch case example but this time with break statements:

public class SwitchCase_Example2b {




  public static void main(String[] args) {

    int day = 4;

    switch (day) {

      case 1:

        System.out.println("Monday");

        break;

      case 2:

        System.out.println("Tuesday");

        break;

      case 3:

        System.out.println("Wednesday");

        break;

      case 4:

        System.out.println("Thursday");

        break;

      case 5:

        System.out.println("Friday");

        break;

      case 6:

        System.out.println("Saturday");

        break;

      case 7:

        System.out.println("Sunday");

        break;

      default:

         System.out.println("Incorrect Number");

    }

  }

}

Output:

Thursday

Now you can see that only case 4 had been executed, the rest of the cases were ignored. Hence, only Thursday will be printed on the screen.

Do we use break statement after default?

The break statement is not required following default because the control would itself come out of the switch after the default case, however, if you still use the break after default, it will not cause a syntax error.

If the default case is used in between the cases then it will be compulsory to use a break statement at the end to stop the flow of the program like with any other case.

Few characteristics of switch case in Java

Order is not required:

Switch case in Java does not need to have cases in any order. It can have any unique value as a case keyword. Also, the cases do not need to be in ascending order, you can specify them in any order based on the requirements of the code.

Use of characters in switch case.

Just like an integer, characters can also be defined as cases.

See this code below:

public class SwitchCase_Example3 {

   public static void main(String args[]){

      char Grade ='A';

      switch(ch)

      {

          case 'A':

            System.out.println("Remarks : Excellent");

            break;

          case 'B':

            System.out.println("Remarks : Fair ");

            break;

          case 'C':

            System.out.println("Remarks : Satisfactory ");

            break;

          case 'D':

           System.out.println("Remarks : Need Improvement ");

           break;

          default:

            System.out.println("No Remarks ");

      }

   }

}

Output:

Remarks: Excellent

Switch expression must be a constant value:

The statement or variable used as a switch expression must be a constant value otherwise it would not be valid. In the case of using a variable, the value must be set before initiation of switch case, must be of same data type and it must not be altered any where in the code later.
For example:

These are some valid expressions for the switch:

int num = 3;



switch(num)

switch(4*2+num)

switch(2+3)

Following expressions would be Invalid:

switch(ab+cd)

switch(a+b+c)

Note: here, a,b,c values are not defined

Nesting of switch case in Java:

Nesting is permitted with the Java switch statement, which means you can have switch statements inside one of the switch cases. However, the nested Java switch statement should be used only when required or when you are certain about it as it would make the program way more complex and less readable.

See this Java switch case example below:

public class SwitchCase_Example4 {

{

   public static void main(String[] args)

   {

      int year = 3;

      int marks = 60;

      switch(year)

      {

        case 1:

         System.out.println("You are not eligible for the scholarship ");

         break;

        case 2:

         System.out.println("You are not eligible for the scholarship");

         break;

        case 3:

         switch(marks/10)

         {

           case 9:

            System.out.println("Congratulations. You are eligible for the scholarship.");

           case 10:

            System.out.println("Congratulations. You are eligible for the scholarship.");

            break;

            default:

            System.out.println("Your marks are insufficient for the scholarship.");

         }

         break;

         default: System.out.println("Please enter the valid year of education.");

     }

   }

}

Output:

Your marks are insufficient for the scholarship.

Here, the nesting is properly executed for two conditions, for checking year of education should be 3rd and the marks must be 90 or above. However, if the conditions would be different then the nested Java switch statement might not be that suitable for it.

If statement VS switch case in Java:

Java ‘If’ statements or Java switch statement, both can be used in almost every conditional situation but there are certain things to be considered while choosing one of them. Switch case shines in the scenarios with more options, it not only makes the code more readable but also keeps it easier to write. Unlike ‘If’ statement, a Java switch statement can have several possible execution paths. On the contrary, ‘If’ statements come in handy when you need to use a range in your conditions as switch expression only allows a fixed value.

See Also: 20 Useful Libraries Java Programmers Should Know

Wrapping it up

We have discussed all that you need to know about how to implement a Java switch statement. If used correctly, switch case in Java can have endless possible applications for executing conditions. It can be used with loops or with several other conditional statements to create an efficient and robust Java code.

Author

Shaharyar Lalani is a developer with a strong interest in business analysis, project management, and UX design. He writes and teaches extensively on themes current in the world of web and app development, especially in Java technology.

Write A Comment