, , , ,

Here we see the features and enhancements made in Java 7. Click here to see the example on file watcher service enhancement made in java 7 from my previous post.

Diamond Operator

Java 5 introduced a feature called generics. As part of this enhancement you could have seen your application has the line like below.
Map<String, List<Person>> persons = new TreeMap<String, List<Person>> ();

If you dont specify the types in generics, your IDE throw warnings when you use the object like below.
       “Type safety: The method put(Object, Object) belongs to the raw type Map. References to generic type Map<K,V> should be parameterized”

The not-so-nice thing about this declaration is that we must declare the types on both the sides, although the right-hand side seems a bit redundant. Can the compiler infer the types by looking at the left-hand-side declaration? Not unless you’re using Java 7. In 7, it’s written like this:

Map<String, List<Person>> persons = new TreeMap <> ();

You don’t have to type the whole list of types for the instantiation. Instead you use the <> symbol, which is called diamond operator. Note that while not declaring the diamond operator is legal, as persons = new TreeMap (), it will make the compiler generate a couple of type-safety warnings.

Strings in switch statements

The traditional jdk allow only int and enum constants inside switch statement. If you wanted to perform nested conditions dealing with Strings, nested if-else statement is the only option.

But in JDK 7, you can use string variables in switch statements like below.

public void processData(Values v) {
String value = v.getValue();
switch (value) {
case “one”:
System.out.println(“value is one”);
case “two”:
System.out.println(“value is two”);
case “three”:
System.out.println(“value is three”);

In the above program, the value field is always compared against the case label by using the String.equals() method.
When you use eclipse IDE lower than version 3.7, you will get compile time exception though you use JDK 1.7 since eclipse version greater than 3.7 only supports this feature. It works fine in command line.