That’s right, Java 7 is just around the corner. Here’s a few of the new language features that I really like:

Match on Strings in a switch statement

No longer do we have to write those ugly case statements like the one shown below. Some people put the variable and the constant the other way around, but then you might get a NullPointerException, so you have to check for that too, which is even more ugly. I prefer to do it the way shown, but every time I type one, I can’t help feeling a little bit of distaste.

Try with resources

Java 7 introduces a ‘try with resources’ construct which allows us to define our resources for a try block and have them automatically closed after the try block is completed – either successfully or when an exception occurs. This makes things a lot neater. Let’s take a look at the example below which include both the ‘old’ way and the ‘new’ way:

We are forced to declare our resource in the scope outside the try so that it will still be visible in the finally,

We have to assign it a null value, otherwise the compiler will complain (correctly) that it may not have been initialized when we try to use it in the finally block,

We need to write a finally block to clean up after ourselves,

In our finally block, we first have to check if things worked or not, and if they did not, then we have to clean up,

We need another try inside the finally since the cleanup operation in the finally is usually that could throw another exception!

The new way is a lot cleaner. We simply define our resources in parentheses after the try and before the opening brace of the try code block. Multiple resources can be declared by separating them with a semicolons (;). No need to define the resource in the outer scope (unless you actually want it to be available out there).

Also, you don’t have to write a finally block at all. Any resources defined this way will automatically be released when the try block is finished. Well not any resource, but any that implement the java.lang.AutoCloseable interface. Several standard library classes, including those listed below, implement this interface.

java.nio.channels.FileLock

javax.imageio.stream.ImageInputStream

java.beans.XMLEncoder

java.beans.XMLDecoder

java.io.ObjectInput

java.io.ObjectOutput

javax.sound.sampled.Line

javax.sound.midi.Receiver

javax.sound.midi.Transmitter

javax.sound.midi.MidiDevice

java.util.Scanner

java.sql.Connection

java.sql.ResultSet

java.sql.Statement

Much nicer!

Catch multiple-type exceptions

Ever found yourself writing a whole heap of catch blocks with the same code in them, just to handle different types of exceptions? Me too! Java 7 provides a much nicer way to deal with this:

You can list the types of exceptions you want to catch in one catch block using a pipe (|) separator. You can still have other catch blocks as well.

Type Inference

I never thought I would see the day and it is still a long way away from the type inference in languages like Scala, but we can now omit types when initializing a generic collection. One small step for Java… one huge leap for mankind!

Map&lt;String, List&lt;String&gt;&gt; stuff = new HashMap&lt;&gt;();

The ‘diamond operator’ (<>) is used for type inference. Saves a bunch of wasteful typing. However, it only works when the parameterised type is obvious from the context. So this wont compile:

Why? The addAll() method has a parameter of Collection<? extends String>. In the first example, since there is no context, the compiler will infer the type of new ArrayList<>() in the second line to be ArrayList<Object> and Object does not extend String.

The moral of the story: just because you might be able to use <> in a method call – probably you should try to limit its use to just variable definitions.

Nicer Numeric Literals

There are also a couple of small enhancements to numeric literals. Firstly, support for binary numbers using the ‘0b’ prefix (C programmers everywhere breathe a sigh of relief) and secondly, you can put underscores (_) between digits to make numbers more readable. That’s between digits only, nowhere else, not first, or last, or next to a decimal point or type indicator (like ‘f’, ‘l’, ‘b’, ‘x’).

Here are some examples:

// this is a valid AMEX number used for test transactions, you can't buy anything with it
// but it will pass the credit card number validation tests
long myCreditCardNumber = 3782_822463_10005L;
long myNameInHex = 0x4D_41_52_4B;
long myNameInBinary = 0b01001101_01000001_01010010_01001100;
long populationOfEarth = 6_852_472_823L;
// I glad I didn't have to count this!

New Look and Feel for Swing

There is a new look and feel for Swing (which it desperately needed!) called ‘Nimbus.’ It looks a bit like this:

Or this:

It was kinda there as a draft for a little while already in Java 6. Why is it good? It can be rendered at any resolution, and it is a lot faster (yeah!) and arguably better looking that those boring old ones!

Better parallel performance

I attended a presentation by Doug Lea a couple of days ago, and he told us proudly that Java 7 also has some of his code buried in there that has long been waiting to see the light of day. A new work stealing queue implementation in the scheduler which should provide a good boost to performance of parallel tasks. This should be especially helpful as we write more and more parallel software in these days of more cores rather than higher frequencies. Especially nice if you are writing using an easy concurrent programming model like Actors in Scala, but still good if you are struggling through threads, locks, latches and all that. Thanks Doug!

Summary

Well there you have, a few small steps forward. I am looking forward to seeing a few bigger steps in Java 8!

Share this:

Like this:

LikeLoading...

Related

About Mark Nelson

Mark Nelson is an Architect (an "IC6") in the Fusion Middleware Central Development Team at Oracle. Mark's job is to make Fusion Middleware easy to use in the cloud and at home, for developers and operations folks, with special focus on continuous delivery, configuration management and provisioning - making it simple to manage the configuration of complex environments and applications built with Oracle Database, Fusion Middleware and Fusion Applications, on-premise and in the cloud. Before joining this team, Mark was a senior member of the A-Team since 2010, and worked in Sales Consulting at Oracle since 2006 and various roles at IBM since 1994.

Copyright 2009-2015 Mark Nelson, Tanya Williams and other contributors. All Rights Reserved. The views expressed in this blog are our own and do not necessarily reflect the views of Oracle Corporation. All content is provided on an 'as is' basis, without warranties or conditions of any kind, either express or implied, including, without limitation, any warranties or conditions of title, non-infringement, merchantability, or fitness for a particular purpose. You are solely responsible for determining the appropriateness of using or redistributing and assume any risks.

The header image is a photograph of a house in China, taken by one of my favourite photographers, Roland Slee. Used with permission. Copyright Roland Slee.

About Advertising

WordPress does not allow blog owners to advertise on blogs hosted on wordpress.com, however they do sometimes inject their own advertisments into some pages for some users in order to produce revenue to support the great service they provide to us at no charge. WordPress provide blog owners with the ability to opt-out of this advertising for a small yearly fee. We prefer not to have advertisements displayed to readers of our blog and have opted out for your viewing pleasure.