String Switch support

Every version of Java brings some new features to make Java coding simple to practice. JDK 1.7 brought many features and one among is switch statement. Switch is a control structure existing in all programming languages where a switch parameter should be an integer value or convertible to integer. If you pass a char, it is converted into integer implicitly. If you pass a long data type, it raises compilation error; of course in particular to Java.

In JDK 1.7 (known as Java 7), the switch statement takes a string as parameter. Surprising, it is true.

1. String in Switch Expression

Earlier to JDK 1.7, switch expression takes int values or convertible to int. From JDK 1.7, switch accepts string objects also as expression.

Example on String Switch support
public class SwitchStrings
{
  public static void main(String args[])
  {
    String str1 = "August";
    String str2 = "";

    switch(str1)                // observe, string passed as parameter (String Switch support)
    {
      case "January":		str2 = "1st";  break;
      case "February":   	str2 = "2nd";  break;
      case "March":   		str2 = "3rd";  break;
      case "April":   		str2 = "4th";  break;
      case "May":   		str2 = "5th";  break;
      case "June":   		str2 = "6th";  break;
      case "July":   		str2 = "7th";  break;
      case "August":   		str2 = "8th";  break;
      case "September":   	str2 = "9th";  break;
      case "October":   	str2 = "10h";  break;
      case "November":   	str2 = "11th"; break;
      case "December":   	str2 = "12th"; break;
    }
    System.out.println(str1 + " is " + str2 + " month in the year");
  }  
}


String Switch support
Output screenshot on String Switch support

All the Java 7 features including more switch statements are discussed in JDK 1.7 Features.

Leave a Comment

Your email address will not be published.