Language enhancements

Java 7 includes a few new language features via Project Coin. These features are quite handy for a developer.

Diamond Operator

You may have noted on many occasions your IDE complaining of types when working with Generics. For example, if we have to declare a map of trades using Generics, we write the code as follows:

Map<String, List<Trade>> trades = new TreeMap<String, List<Trade>> ();

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<Trade>> trades = new TreeMap <> ();

How cool is that? 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 trades = new TreeMap (), it will make the compiler generate a couple of type-safety warnings.

Using strings in switch statements

Switch statements work either with primitive types or enumerated types. Java 7 introduced another type that we can use in Switch statements: the String type.

Say we have a requirement to process a Trade based on its status. Until now we used to do this by using if-else statements.

private void processTrade(Trade t) {
            String status = t.getStatus();
            if (status.equalsIgnoreCase(NEW)) {
                  newTrade(t);
            } else if (status.equalsIgnoreCase( ...

Get What's New in Java 7 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.