The switch Statement (Cont.)


String in Switch Cases
We can use a string literal/constant to control a switch statement, which is not possible in C/C++. Using a string-based switch is an improvement over using the equivalent sequence of if/else statements:
StringCase.java (string cases in a switch statement)
// Demonstration of the use of string cases in a switch statement
public class StringCase { 
  public static void main( String[ ] args ) { 
    switch( args[0] ) { 
      case "Monday": 
        System.out.print( args[0].compareTo("Monday") ); 
        break;
      case "Tuesday":
        System.out.print( args[0].contains("day") );
        break;
      case "Wednesday":
        System.out.print( args[0].equals("Wednesday") );
        break;
      case "Thursday":
        System.out.print( args[0].indexOf("day") );
        break;
      case "Friday":
        System.out.print( args[0] == "Friday" );
        break;
      default: 
        System.out.print( args[0] != "Sunday" ); 
    } 
  }
}
shell> java StringCase  

Output:             Result:




      All it’s cracked up to be.