Switch on Strings in Java

By Prasanna LM | Jan 24, 2008


JDK 5.0 and its implementation of enum has eased the process of switching on strings in Java. Following code snippet shows how this functionality can be achieved..

public class prasTest {

public enum test {
first, second, third, novalue;

public static test toValidStr(String str) {
try {
return valueOf(str);
}
catch (Exception e) {
return novalue;
} }
}

public static void main(String args[]) {
String str = “second”;
switch (test.toValidStr(str)) {
case first:
System.out.println(“first”);
break;
case second:
System.out.println(“second”);
break;
case third:
System.out.println(“third”);
break;
default: System.out.println(“default”);
break;
} } }

Here, in the above implementation we could have directly used enum.valueOf() in switch statement instead of toValidStr() but, just to handle the IllegalArgument Exception which is thrown when some non-enum string is given as the input to switch, a new static method (toValidStr() ) is created and used. Enum.valueOf() method matches the given string to the actual enum string using the hashcode matching mechanism . The maintenance of possible string values is also eased and more structured with the use of enums.


About the author

Prasanna LM is a programmer & a tech enthusiast working from Bangalore, India. He is a Sun Certified Java Programmer & he is passionate about developing software's using Java & JEE related technologies.

Share and Enjoy:
  • StumbleUpon
  • Facebook
  • TwitThis
  • Digg
  • Technorati
  • del.icio.us
  • LinkedIn
  • MySpace
  • Reddit
  • YahooMyWeb
  • Yahoo! Buzz

Related Posts

Leave a Comment

If you would like to make a comment, please fill out the form below.

Name (required)

Email (required)

Website

Comments

© 2010 TechSagar, Privacy Policy