In this section, you will learn about strings in switch statements which is recently added feature in Java SE 7.
Strings in Switch statement
In this section, you will learn about strings in switch statements which is recently added feature in Java SE 7.
Using JDK 7, you can pass string as expression in switch statement. The switch statement compares the passed string with each case label and execute the case block which have matched string. The comparison of string in switch statement is case sensitive.
The example code for the above is given below :
public class StringsInSwitch { public String getTypeOfDayWithSwitchStatement(String dayOfWeekArg) { String typeOfDay; switch (dayOfWeekArg) { case "Monday": typeOfDay = "Start of work week"; break; case "Tuesday": case "Wednesday": case "Thursday": typeOfDay = "Midweek"; break; case "Friday": typeOfDay = "End of work week"; break; case "Saturday": case "Sunday": typeOfDay = "Weekend"; break; default: throw new IllegalArgumentException("Invalid day of the week: " + dayOfWeekArg); } System.out.println(typeOfDay); return typeOfDay; } public static void main(String args[]) { new StringsInSwitch().getTypeOfDayWithSwitchStatement("Friday"); } }
OUTPUT
C:\Program Files\Java\jdk1.7.0\bin>javac
StringsInSwitch.java C:\Program Files\Java\jdk1.7.0\bin>java StringsInSwitch End of work week |