JDK7 examples of new features

26 Feb 2011

Java 7 was released to developers this week (Java 6 was released in Dec 2006). From what I've read, it's not too exciting. It has some new features like TLS 1.2 support for more secure network transactions, and some features to save typing for example:

Diamond collections don't need to repeat types

// JDK6
List<String> l = new LinkedList<String>();
// JDK7
List<String> l = new LinkedList<>();

try's can be told what resources to clean-up without a finally

// JDK6
BufferedReader br = new BufferedReader(new FileReader(path));
try {
  return br.readLine();
} finally {
  br.close();
}

// JDK7
try (BufferedReader br = new BufferedReader(new FileReader(path)) {
 return br.readLine();
}

Collection literals

// JDK6
List<Integer> piDigits = Collections.unmodifiableList(Arrays.asList(3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 9 ));
// JDK7
List<Integer> piDigits = {3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 9};

Binary support... sort of

It'd be awesome if Java would actually support byte's as primitives and unsigned values. My favorite rant on this is from the Insanely Low Level blog's post.

// JDK6 (this or similar awkwardness)
int binary = (1<<3) | (0 << 2) | (0 << 1) | (1 << 0);
// JDK7
int binary = 0b1001;

Underscores in numbers

Not very exciting at all, but weird when you encounter it.

// JDK6
int ssn = 123456789;
// JDK7
int ssn = 123_45_6789; // underscores get ignored