Best Practices from Oracle Development's A‑Team

Java 7 is nearly here…

Mark Nelson


That’s right, Java 7 is just around the corner.

Main article

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.

case ("something".equals(whatever));

But now, we can write these much more elegantly. Here is an example:

public class Test {   public static void main(String[] args) {   if (args.length != 1) {  System.out.println("You must specify exactly one argument");   System.exit(0);   }   switch (args[0]) {   case "fred":   System.out.println("Hello fred");   break;  case "joe":   System.out.println("Hello joe");   break;   default:   break;   }   }  }

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:

import java.io.File;  import java.io.FileInputStream;  import java.io.InputStream;  import java.io.IOException;  import java.io.FileNotFoundException; public class Try {   public static void main(String[] args) {   // the old way...  InputStream oldfile = null;   try {   oldfile = new FileInputStream(new File("myfile.txt"));   // do something with the file   } catch (IOException e) {   e.printStackTrace();   } finally {   // we need to check if the InputSteam oldfile is still open    try {   if (oldfile != null) oldfile.close();   } catch (IOException ioe) {   // ignore  }  }  // the new way...  try (InputStream newfile = new FileInputStream(new File("myfile.txt"))) {  // do something with the file  } catch (IOException e) {  e.printStackTrace();  }  // the InputStream newfile will be closed automatically  }  }

When we do things the old way, there are a few areas of ugliness:

  • 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:

try {  // do something  } catch (JMSException | IOException | NamingException e) {   System.out.println("Oh no! Something bad happened");   // do something with the exception object...   e.printStackTrace();  }

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 daywlemoticon-smile 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<String, List<String>> stuff = new HashMap<>();

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:

List<String> list = new ArrayList<>();  list.addAll(new ArrayList<>());

But this will:

List<String> list = new ArrayList<>();  List<? extends String> list2 = new ArrayList<>();  list.addAll(list2);

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!


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

Be the first to comment

Comments ( 0 )
Please enter your name.Please provide a valid email address.Please enter a comment.CAPTCHA challenge response provided was incorrect. Please try again.Captcha