Social Icons

twitterfacebookgoogle pluslinkedinrss feed Online Resume

Monday, September 14, 2015

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);
 }
}

Friday, September 11, 2015

Java7 : Multiple Catch Block with example


With JAVA SE 7, Multi-catch exceptions handling has been introduced and it is a convinent way for exception handling, since we can catch multiple exceptions using one catch block.

In the "Multi-catch" block each exception should be separated by pipe (|) charatcter and that will make code is more readable.

Read more : Working with Java SE 7 

Ex:
public class SampleClass {
 public static void main(String[] args) {
  try {
   // Your code
  } catch (ParseException | IOException exception) {
   // inside the multie catch block
  }
 }
}