4.4.Using Strings in switch Statements
As of Java SE 7, you can use a String object in the argument of a switch statement. This piece of code, StringSwitchDemo, shows the month’s number based on the value of the String called month:
public class StringSwitchDemo { public static int getMonthNumber(String month) { int monthNumber = 0; if (month == null) { return monthNumber; } switch (month.toLowerCase()) { case "january": monthNumber = 1; break; case "february": monthNumber = 2; break; case "march": monthNumber = 3; break; case "april": monthNumber = 4; break; case "may": monthNumber = 5; break; case "june": monthNumber = 6; break; case "july": monthNumber = 7; break; case "august": monthNumber = 8; break; case "september": monthNumber = 9; break; case "october": monthNumber = 10; break; case "november": monthNumber = 11; break; case "december": monthNumber = 12; break; default: monthNumber = 0; break; } return monthNumber; }
public static void main(String[] args) { String month = "August"; int returnedMonthNumber = StringSwitchDemo.getMonthNumber(month); if (returnedMonthNumber == 0) { System.out.println("Invalid month"); } else { System.out.println(returnedMonthNumber); } } }
This code generates an output of 8.
The expressions associated with each case label are compared to the String in the switch expression, as if the String.equals method were being employed. The StringSwitchDemo example is capable of accepting any month, regardless of case, by converting it to lowercase using the toLowerCase method. Additionally, all strings associated with the case indicators are in lowercase.
Note: This example determines whether the expression in the switch statement is null. Ensure that the expression in any switch statement is not null in order to prevent the occurrence of a NullPointerException.