Friday, December 21, 2012

Java 7's Best New Features

Java 6 is approaching its end of life release in February 2013, so here are some new features of Java 7 that will help you hit the ground running with the new JDK. A few of them are sure to be huge timesavers, like using Strings in switch statements.

Binary Literals

int j = 0b10101010101;

Underscores in Numbers

Let you quickly see how large a number really is.
int k = 1_000_000;

String Switch Statements

Use the new string switch statements to apply .equals() on the string:
switch(someString)
{
case "Saturday": case "Sunday":
return "weekend";

default:
return "weekday";
}

Automatic Resource Closing

When you open streams in try blocks, they are now automatically closed.
try(InputStream in = socket.getInputStream();
PrintStream out = new PrintStream(new BufferedOutputStream(socket.getOutputStream())))
{
byte[] b = new byte[1024];
int k = 0;
while((k = in.read(b)) > 0)
out.write(b,0,k);
}

// in and out will be cleaned up after this.

Multiple Catch

You can now catch more than one exception at a time:
try{

// do stuff here

}catch(IOException | NullPointerException ex)
{
// Handle either exception
}

New Diamond Operator

No longer do you have to declare the same type in the constructor and variable when you're providing types:
HashMap<String, Integer> myMap = new HashMap<>();

NIO

This is a huge topic, too long to be covered here; but there is a new library for working with various filesystems that abstracts away their differences, so you can use the same code to work remotely, locally, within zip files, etc.

Compute/Fork Join

Java now provides an interface for embarrassingly parallel fork-join tasks (such as sorting), just implement Compute.

Swing Improvements

  • Draw on top of components, then erase the drawing, using JLayer
  • Make translucent windows with .setOpacity(<float>) on a JFrame
  • New HSV tab on JColorChooser.

No comments:

Post a Comment