Sunday, January 8, 2012

Java 7 new features - 1. Switch on Strings


<< Previous Table of Categories Next >>


 
   /**
      * If you have any comments or better examples, please paste on my blog:
      * http://blog.yanmingyu.com or email me feedback.andrewyu@gmail.com
      * 
      * From Java 7, developers can use "switch" statement on String.
      * Please refer to the following example about how to use it.
      */
  public static String getAustralianCapitalCity(String stateOrTerritory)
  {
    String capitalCity = "unknown";
    switch (stateOrTerritory)
    {
      case "NSW":
      case "New South Wales":
        capitalCity = "Sydney";
        break;
      case "QLD":
      case "Queensland":
        capitalCity = "Brisbane";
        break;
      case "VIC":
      case "Victoria":
        capitalCity = "Melbourne";
        break;
      case "SA":
      case "South Australia":
        capitalCity = "Adelaide";
        break;
      case "TAS":
      case "Tasmania":
        capitalCity = "Hobart";
        break;
      case "NT":
      case "Northern Territory":
        capitalCity = "Darwin";
        break;
      case "ACT":
      case "Australian Capital Territory":
        capitalCity = "Canberra";
        break;
      default:
        break;
    }
    return capitalCity;
  }

1 comment: