Home Java Jdk7 Strings in Switch statement
Questions:Ask|Latest


 
 

Share on Google+Share on Google+

Strings in Switch statement

Advertisement
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

Download Source Code


Advertisement

Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: September 2, 2011

Ask Questions?    Discuss: Strings in Switch statement  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
rangga
September 29, 2011
error

public class StringsInSwitch{ ^ 1 error
DMCA.com