The String in Switch Case in Java


The introduction of Java 7 enhanced the switch case i.e. it support string as well.

At first, set a string −

String department = "AKD05";

Now, use the same string in switch as shown below −

switch(department)

Example

Now, check for every string using case as we normally do while using SWITCH CASE. Following is an example to implement String in Switch Case −

public class Demo {
   public static void main(String[] args) {
      String department = "AKD05";
      switch(department) {
         case "AKD01":
            System.out.println("Finance");
            break;
         case "AKD02":
            System.out.println("Sales");
            break;
         case "AKD03":
            System.out.println("Production");
            break;
         case "AKD04":
            System.out.println("Marketing");
            break;
         case "AKD05":
            System.out.println("Operations");
            break;
         default:
            System.out.println("None!");
      }
   }
}

Output

Operations

Updated on: 25-Sep-2019

193 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements