ABIS Infor - 2013-01

New features in Java SE7

Sandy Schillebeeckx (ABIS) - 29 January 2013

Abstract

Java SE7 (codename Dolphin) is actually not that new any more. It was released on 7/7/2011, but certainly not everybody is fully using it yet.

Since Oracle announced the end of support for JDK1.6 as of February 2013, you even have less of an excuse not to adopt it. And why wouldn't you try out some of the nice new features? In this version of Java, they didn't just add interesting classes (like in NIO, JDBC, Concurrency), but they also introduced some new things in the programming language itself.

Language enhancements

Java SE7 adds a couple of changes to the programming languages itself. All of those were released as part of Project Coin.

Allowing underscores in numeric literals

The moment you start writing big numbers, they can become less readable. For instance 10000000. Is that 100 million or 10 million? You have to start counting zeroes to be sure. To make it easier for you, Java now allows you to use underscores in numbers, like this:

int i = 10_000_000;

A lot clearer, don't you think?

Binary integer literals

Like octal (int myOct = 016) and hexadecimal (int myHex= 0x16), you can now also define binary numbers:

int mybin = 0b1001_1001;

Also here you can use underscores.

Type inference for generic instance creation ("diamond syntax")

Instead of writing

ArrayList<String> list= new ArrayList<String>() , 

you can now write:

ArrayList<String> list= new ArrayList<>().

This is called the diamond syntax. It doesn't seem that spectacular, but in case of:

HashMap<String,List<Integer>> someMap = new HashMap<>() , 

it can be quite handy. All in the philosophy: "a good programmer is a lazy programmer" of course.

Switch on strings

This is one of the things were you could say "finally, why didn't they introduce this before". Only ints or Enums were possible up to now. Seems that one of the reasons it was held back is performance.

But here it is:

public void chooseDomain(String s){
	switch (s.toLowerCase()) {
case "java" : this.javaAction(); break;
case "unix" : this.unixAction(); break;
case "databases" : this.databaseAction(); break;
default : System.out.println("nothing or other domain chosen");
} }

The compiler uses hashCode() and equals() in the background to check the equality with the incoming value.

But watch out: if you pass through null as a parameter (e.g. obj.chooseDomain(null)), you will get a NullPointerException! You can not use null as a case in the switch statement.

If you want to go for type safety, Enums actually still are the best option.

Automatic resource management in try-statement

Exception handling when using resources (IO, database connections) can become quite extensive. You have to write lots of boilerplate code making sure all resources are closed correctly.

That's why Java SE7 introduced automatic resource management (ARM).

Behind the scenes the IO classes implement java.lang.AutoCloseable to make it happen.

The syntax is as follows:

try (LineNumberReader lnr = new LineNumberReader(new FileReader("somefile.txt"));) {
String s;
while ((s=lnr.readLine()) != null){
Integer.parseInt(s);
}
} catch (IOException) {
e.printStackTrace();
}

Catching multiple exception types

A single catch block can now handle more than one exception. Each exception type is separated with a vertical bar ("|").

The catch parameter (se) is in this case implicitly final.

try {
someProp.doFirstThing();
someProp.doSecondThing();
} catch (SomeException1 | SomeException2 se) {
System.out.println(e.getMessage());
}

Library additions

NIO.2

In previous versions of Java, there were already a lot of classes handling I/0 in the java.io and java.nio. But there were still some caveats and problems, certainly when working on different platforms. One of the problems for instance was that the rename method for files wasn't consistent across platforms. Other methods did not throw exceptions when they failed. On top of that, more support for metadata was desired, such as file permissions, file owner, and other security attributes.

The new java.nio.file package provides extensive support for file and file system I/O. It is a huge API, but the main classes are the following:

  • The Path interface has methods for manipulating a path. You can look at a path as being a logical name for a file or directory. Some interesting methods are: getParent(), getRoot() and relativize() (finds the relative path from one file to another).
  • The Files class has a bunch of static methods for all kinds of file operations. Most of them take a Path as a parameter. First of all the methods createFile() and createDirectory() to turn a Path into "the real thing". Operations such as moving (renaming), copying and deleting can be done, and also methods for retrieving and setting file attributes are foreseen.
  • The FileSystem class has a variety of methods for obtaining information about the file system.
  • By using the WatchService interface, you can monitor a file or directory for changes.

Concurrency utilities

The fork/join framework is designed to efficiently run a large number of tasks using a pool of worker threads. A bigger task is recursively broken up into smaller pieces. You can make use of multiple processors so performance can increase dramatically. Main classes are ForkJoinPool and ForkJoinTask.

Dynamic language support

In previous releases of Java, the JVM already supported the use of dynamic languages like JRuby, Groovy and Python. But there was a small performance penalty in doing so. The JVM invokedynamic method now allows dynamic, direct linkage. Invoking code in other languages is now equivalent to straight Java method calls.

On top of that, a new package, java.lang.invoke, containing classes like MethodHandle and CallSite, has been created to extend the support of dynamic languages.

Conclusion

As you can see, Java SE7 added some nice new features. They made another step in ease of development and improved performance. And there is more to come in Java SE8, which will be released around September 2013. Some of the promising new stuff there are the new Date&Time API and the introduction of lambda expressions ("closures").