switch for string in java code example

Example 1: Java switch case with string

// Java switch case with string
public class SwitchCaseWithString 
{
   public static void main(String[] args) 
   {
      String str = "twelve"; 
      switch(str) 
      { 
         case "ten": 
             System.out.println("ten"); 
             break;
         case "eleven": 
             System.out.println("eleven"); 
             break;
         case "twelve": 
             System.out.println("twelve"); 
             break; 
         default: 
             System.out.println("doesn't match"); 
      }
   }
}

Example 2: switch case mit string

public String getTypeOfDayWithSwitchStatement(String dayOfWeekArg) {
     String typeOfDay;
     switch (dayOfWeekArg) {
         case "Monday":
             typeOfDay = "Start of work week";
             break;
         case "Tuesday":
         case "Wednesday":
         case "Thursday":
             typeOfDay = "Midweek";
             break;
         case "Friday":
             typeOfDay = "End of work week";
             break;
         case "Saturday":
         case "Sunday":
             typeOfDay = "Weekend";
             break;
         default:
             throw new IllegalArgumentException("Invalid day of the week: " + dayOfWeekArg);
     }
     return typeOfDay;
}

Tags:

Java Example