Monday, February 3, 2014

Some new features in Java 7 - Part 1

String in switch statements

Java 7 has introduced String in switch statements.

e.g.

if (color.equals("RED")){

    //code
} else if (color.equals("BLUE")){
   
    //code
} else if (color.equals("GREEN")){
   
    //code
}

Numerics with underscore _

Java 7 introduced underscores in numerical literals.

int thousand = 1_000;

OR

int million = 1_000_000;


Multi catch feature

Java 7 introduced multi-catch functionality to catch multiple exception types using a single catch block

If your code has two exceptions:

try {

//code

} catch (Exception1 e ){
   
    // log
   
} catch (Exception2 ex){

    //log

}

There is duplication of code sometimes in all the catch block.
Of course one could just catch generic Exception

catch (Exception e)

In Java 7, you could use the delimiter | for multiple exceptions of same type

try {

//code

} catch (Exception1 | Exception2 e){
   
    // log
   
}

If you have different types of exceptions, then use multi catch


try {

//code

} catch (Exception1 | Exception2 e){
   
    // log
   
} catch (Exception3 | Exception4 ex){
   
    // log
   
}

No comments:

Post a Comment