Switch on Strings in Java

By | 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 Software Engineer and a Tech Enthusiast from Bengaluru,India. He is also the founder and Chief Blogger at TechSagar.com. He specializes in developing softwares using Java and related technologies. He spends most of his free time in exploring new technologoes around the world wide web. He also advices novice bloggers in setting up their self hosted blogs using WordPress.

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

© 2011 TechSagar, Privacy Policy