Studyon Minte9.com
Java SE




Switch



Simple switch with string not supported for JDK version < 7

Workaround:

package testexample; public class Test { private enum Action { OPEN, EDIT, EXIT } public static void main(String[] args) { switch(Action.valueOf("EXIT")) { case OPEN: System.out.println("Action is 1"); break; case EXIT: System.out.println("Action is 2"); break; default: } // Output: // Action is 2 } }
  If value not exists
package testexample; public class Test { private enum Action { OPEN, EDIT, EXIT, NOVALUE; public static Action toAction(String str) { // --- Look Here --- // try { return valueOf(str); } catch (Exception e) { return NOVALUE; } } } public static void main(String[] args) { switch(Action.toAction("xxx")) { // --- Look Here --- // case OPEN: System.out.println("Action is 1"); break; case EXIT: System.out.println("Action is 2"); break; default: System.out.println("Action is empty"); } // Output: // Action is empty } }
 


http://www.xefer.com/2006/12/switchonstring
http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html
http://stackoverflow.com/questions/3827393/java-switch-statement-constant-expression-required-but-it-is-constant
http://stackoverflow.com/questions