Electrotek

From programming to day dreaming

JDK 7 new language features (Project Coin)

Tonight I’ve played a bit with JDK 7 small language changes. I find some of them quite handy.

The new stuff:

I’ve always missed this one – strings in switch:

String string = "foo";

switch (string) {
    case "foo":
        System.out.println("bar");
        break;
}

Readability counts; underscores in numeric literals and nice binary literals (I personally think that the underscores in number literals look a bit ugly/hacky/unclean):

long l = 1111_2222_3333_4444L; // I is card number
double d = 0_0; // I is cute, 1337h4x0r style!
byte b = 0b00101010; // I is binary

System.out.println(l); // 1111222233334444
System.out.println(d); // 0.0
System.out.println(b); // 42

Less code for generics, meet the Diamond operator:

List<String> list1 = new ArrayList<String>(); // Pre JRE 7
List<String> list2 = new ArrayList<>(); // Diamonds are forever

Multi-catch:

try {
    // Uuuuu scary stuff here...
} catch (Exception|Error e) {
    // http://ns.c2.com/cgi/wiki?PokemonExceptionHandling 
}

No tedious resource closing in finally block, less code and it looks much cleaner:

/**
 * AutoCloseable will close the resource when it's not needed.
 * 
 * @see http://download.java.net/jdk7/docs/api/java/lang/AutoCloseable.html
 * 
 * @param file
 * @return
 * @throws IOException 
 */
public static String readFirstLine(String file) throws IOException {    
    try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
        return reader.readLine();
    }
}

Simplified varargs method invocation – haven’t checked this improvement yet.

On the side note – Ubuntu 11.04 and Unity are awesome on my Eee netbook, I’ve been checking Unity during development and I honestly thought it will not be ready for the release.

Advertisement

2 Responses to JDK 7 new language features (Project Coin)

  1. من 2011-08-09 at 08:16:40

    What will happen if I use one of these features in my program and compile it using JDK 7 and try to run it on JRE 6???

    • Viktoras Agejevas 2011-08-09 at 18:38:15

      In that case you would get java.lang.UnsupportedClassVersionError.

      If you would compile with -source 1.6 and -target 1.6, javac would complain, that you have to use -source 7 to enable new features.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.