Monday 4 July 2011

What's Up in Java 1.7

Here's some code examples for the new features in Java 1.7
Support for Collections
Let's write less code when we create a List / Set / Map
List< String> list = ["item"];
String item = list[0];
Set< String > set = {"item"};
Map< String,Integer > map = {"key" : 1};
int value = map["key"];
Automatic Resource Mgt
Below code look's to be verbose for you.. right
BufferedReader br = new BufferedReader(new FileReader(path));
try {
   return br.readLine();
} finally {
   br.close();
}
But you love this below one!!!!
try (BufferedReader br = new BufferedReader(new FileReader(path)) {
   return br.readLine();
}
Improved Type Inference for Generic Instance Creation (diamond)
when you declare the interface of your object, You don't want to repeat when you instantiate the object.
Look's to be great na.....
Map<String,String> hello = new Map<>();
Underscores in numeric literals
int billion = 1_000_000_000;
I am not sure how many ppl it will be useful one?
String's in switch case
String availability = "available";
switch(availability) {
 case "available":
    //code
    break;

  case "unavailable":
    //code
    break;

  case "merged":
    //code

  default:
    //code
    break;
}
Note : Check for the Null in the String before you passing the String into Switch case.
Binary literals
You can create binary literals using the 0b prefix
int binary = 0b1001_1001;
Catching More Than One Type of Exception with One Exception Handler
try {
Here comes your code....
}
catch(IOException | NullPointerException | ..........) {
}

 It would be great if someone can point me on more things. I am sure there are plenty of other cool stuff.

5 comments:

  1. not certain that simple list acces is still in java 7
    i think it has be postponed to 8

    ReplyDelete
  2. This comment has been removed by a blog administrator.

    ReplyDelete
  3. String's in switch case is very useful feature!

    ReplyDelete
  4. If you honestly think that these additions are useful, you should have switched to Scala a while ago ;-)

    ReplyDelete
  5. try with resources and multiple catch blocks are more useful, it's simplified programmers life...thanks for providing this much information and we are waiting for your updates.

    ReplyDelete