Java7: Strings in Switch Statements

Switch statements with String is long waiting enhancement which is requested 1995(Decade before I have joined to IT industry).

This String switch statement uses the equal operation to compare the String object in expression and label. Therefore String switch statement is case sensitive. Also according to the Java documentation, this switch statement is more efficient than if-else statements("Java compiler generates generally more efficient bytecode from switch statements").

Ex:
public void stringSwitchStatement(String value) {
 switch (value) {
  case "Chandana":
   System.out.println("Input is Chandana");
   break;
  case "OtherValue":
  case "OtherValue2":
   System.out.println("Other inputs : " + value);
   break;
  case "Test":
   System.out.println("Input is Test");
   break;
  default:
   throw new IllegalArgumentException("Invalid input value : " + value);
 }
}
Post a Comment

Popular posts from this blog

Yield Price Sri Lanka - Android Application

Manage SOAPAction of the Out Message

How to clean Registry log (REG_LOG) table