Switch case in Java


JavaViews 3153

The switch case statement in Java is similar to if-else if ladder which we have seen in the previous tutorial. When we have multiple conditions and each has a different task, then we use the switch case in java. This is another type of Conditional or Decision-making statement. Switch case in java is more efficient and readable than if-else if ladder in case we are using only the same data type. We use if-else when we need to validate expressions.

Syntax

Below is the syntax of the switch case in Java. It can have multiple case statements each having a unique value. The switch expression or variable validates each case variable and executes the case that has a match.

switch(variable) {
case value1:
  //code
  break; //optional
case value2:
  //code
  break; //optional
default:
  //code

}

Features of Switch case in Java

  • There can be multiple case statements in a switch case in java.
  • Each case statement has a unique value which means it does not allow duplicate values.
  • The case value should be either literal or constant and cannot be a variable.
  • It is optional to have a break statement within every case statement.
  • The parameter of a switch statement can be any variable or integer expression.
  • The switch expression may contain either integer values, string, character, byte, short, long, or enum
  • The case value should match the switch expression type.
  • Switch case in java supports default case value which is optional.
  • When a case has integer values, we can write in any order and not necessarily in ascending order.
  • Switch case in java also supports the nested switch case which means a switch case within another switch case.

Flowchart

Switch case in Java

 

First, the switch case in java evaluates the expression or variable. Then starting from the first case, it checks whether the variable value matches the case value. If it matches, it executes the code inside this case. If there is a break statement, it stops the switch case execution and comes out of the switch case. This means it ignores the other case statements. Suppose the value does not match with the first case value, it checks for the subsequent case values and executes the corresponding statement. If there is no break statement, it executes all the other case statements as well until the end. Switch case in java can contain an optional default case

Simple Switch Case example in Java

Let’s see a simple example of a switch case in java. We have an integer variable number with value as 3. We pass this variable to the switch expression. Each case value has a different integer number along with a default case. It is not necessary that these case statements should be in ascending order. First, it evaluates case 1, since the value is not equal to 3, it validates case 2. Since this is also not equal, it prints the statement in the default case.

Switch case in java executes the default case when none of the cases match the expression or variable in the switch case.

public class SimpleSwitchCaseDemo {

  public static void main(String[] args) {
    int number = 3;
    switch(number) {
    case 1:
      System.out.println("Case 1 Value is " + number);
    case 2:
      System.out.println("Case 2 Value is " + number);
    default:
      System.out.println("Default Value is " + number);
    }
  }

}
Default Value is 3

Switch case example with break statement

First, let’s see an example of a switch case in java without a break statement. In the below code, we have a String variable with value as “red“. In the switch expression we pass this variable color which means, whichever case statement has a matching value with color variable, it executes that case statement. Here, the switch expression matches the case red. Hence in the output, we can see that “You have selected red color” is displayed. Since we have not used a break statement in any of the case statements, the switch case in java executes all the case statements.

public class SwitchCaseBreakDemo {

  public static void main(String[] args) {
    String color = "red";
    switch(color) {
    case "red":
      System.out.println("You have selected red color");
    case "green":
      System.out.println("You have selected green color");
    case "blue":
      System.out.println("You have selected blue color");
    default:
      System.out.println("No matching color");
    }

  }

}
You have selected red color
You have selected green color
You have selected blue color
No matching color

Now, suppose imagine we have given a break statement in all case statements, Let’s see how the output is displayed. In this case, we can see that only the statement inside the case red is displayed. Since we have a break statement, the switch case in java ignores all other cases including the default case. In this way, execution comes out of the switch case.

Break statement saves a lot of execution time since it does not check matches for other cases unnecessarily.

public class SwitchCaseBreakDemo {

  public static void main(String[] args) {
    String color = "red";
    switch(color) {
    case "red":
      System.out.println("You have selected red color");
      break;
    case "green":
      System.out.println("You have selected green color");
      break;
    case "blue":
      System.out.println("You have selected blue color");
      break;
    default:
      System.out.println("No matching color");
    }

  }

}
You have selected red color

Nested Switch case in Java

When we have a switch case within another switch case, we call it as a nested switch case in java. However, we don’t recommend to use this since it can make the code more complex and affect readability.

Example of nested switch case

In the below example we have used a nested switch along with break keyword. The outer switch case is for degree and inner switch case for the course. It first checks the switch case expression degree and finds a case matching the value “BTech”. When the case value matches, it executes the code inside the corresponding case statement. This contains another switch case with a variable course and finds the case matching the value “IT” and executes the corresponding case. Since we have used break statements in both the outer and inner switch cases, it ignores the remaining case values and exits the switch case.

public class NestedSwitchCaseDemo {

  public static void main(String[] args) {
    String degree = "BTech";
    String course = "IT";
    switch(degree){
    case "BE":
      System.out.println("Degree is Bachelors of Engineering");
      switch(course) {
      case "CSE":
        System.out.println("Course is Computer Science Engineering");
        break;
      case "ECE":
        System.out.println("Course is Electronics and Communications Engineering");
        break;
      }
    case "BTech":
      System.out.println("Degree is Bachelors of Technology");
      switch(course) {
      case "IT":
        System.out.println("Course is Information Technology");
        break;
      case "BioTech":
        System.out.println("Course is Biotechnology");
        break;
      }
      break;
    default:
      System.out.println("No matching degree found");
    
        
    }

  }

}
Degree is Bachelors of Technology
Course is Information Technology

Switch case using Enum

We can also use enum values to validate the switch case in java. Below is an example showing how to use switch case in java using enums. First, we declare enum values and retrieve the values into another variable. Using for loop, we navigate through all enum values and print the corresponding full month name using switch case.

We will learn more about enums in a separate tutorial.

public class SwitchCaseEnum {

  public enum month { Jan, Feb, Mar, Apr, May, Jun, July, Aug, Sept, Oct, Nov, Dec}
  public static void main(String[] args) {
    month[] fullmonth = month.values();
    for(month name: fullmonth) {
      switch(name) {
      case Jan:
        System.out.println("Month is January");
        break;
      case Feb:
        System.out.println("Month is February");
        break;
      case Mar:
        System.out.println("Month is March");
        break;
      case Apr:
        System.out.println("Month is April");
        break;
      case May:
        System.out.println("Month is May");
        break;
      case Jun:
        System.out.println("Month is June");
        break;
      case July:
        System.out.println("Month is July");
        break;
      case Aug:
        System.out.println("Month is August");
        break;
      case Sept:
        System.out.println("Month is September");
        break;
      case Oct:
        System.out.println("Month is October");
        break;
      case Nov:
        System.out.println("Month is November");
        break;
      case Dec:
        System.out.println("Month is December");
        break;
      }
    }
    
    

  }

}
Month is January
Month is February
Month is March
Month is April
Month is May
Month is June
Month is July
Month is August
Month is September
Month is October
Month is November
Month is December

Switch case using Wrapper classes

Switch case in Java supports wrapper classes like Byte, Short, Long, and Integer. The below example shows how to use the Integer wrapper class.

public class SwitchCaseWrapperDemo {

  public static void main(String[] args) {
    Integer day = 5;
    switch(day) {
    case 1:
      System.out.println("Sunday");
      break;
    case 2:
      System.out.println("Monday");
      break;
    case 3:
      System.out.println("Tuesday");
      break;
    case 4:
      System.out.println("Wednesday");
      break;
    case 5:
      System.out.println("Thursday");
      break;
    case 6:
      System.out.println("Friday");
      break;
    case 7:
      System.out.println("Saturday");
      break;
    }

  }

}
Thursday

Reference

Translate »