Learning JDK 7 Features Part 1 : Strings in switch Statements
Switch statement is enhanced in JDK 7 with the support of String Object. Prior to it JDK 7 release, switch only supports
byte
, short
, char
, and int
litearls. With this release onwards, we use string objects in switch expressions. Its is same as comparing String.equals method for each case. Please note the comparison is CASE- SENSITIVE. Let see how it works :- private static String getTypeOfSeasonFromSwitch(String monthArg) { String typeOfSeason = null; switch (monthArg) { case "December": case "January": case "Febuary": typeOfSeason = "Winter"; break; case "March": case "April": case "May": typeOfSeason = "Spring"; break; case "June": case "July": case "August": typeOfSeason = "Summer"; break; case "September": case "October": case "November": typeOfSeason = "Autumn"; break; default: throw new IllegalArgumentException("Invalid month: " + typeOfSeason); } return typeOfSeason; }
Comments
Post a Comment