Friday, December 2, 2011

Java 7: Project Coin in code examples

This blog introduces - by code examples - some new Java 7 features summarized under the term Project Coin. The goal of Project Coin is to add a set of small language changes to JDK 7. These changes do simplify the Java language syntax. Less typing, cleaner code, happy developer ;-) Let's look into that.


Prerequisites

Install Java 7 SDK on your machine
Install Eclipse Indigo 3.7.1

You need to look out for the correct bundles for your operating system.

In your Eclipse workspace you need to define the installed Java 7 JDK in your runtime. In the Workbench go to Window > Preferences > Java > Installed JREs and add your Java 7 home directory.


Next you need to set the compiler level to 1.7 in Java > Compiler.


Project Coin

Improved literals

A literal is the source code representation of a fixed value.

"In Java SE 7 and later, any number of underscore characters (_) can appear anywhere between digits in a numerical literal. This feature enables you to separate groups of digits in numeric literals, which can improve the readability of your code." (from the Java Tutorials)

public class LiteralsExample {

 public static void main(String[] args) {
  System.out.println("With underscores: ");
  
  long creditCardNumber = 1234_5678_9012_3456L;
  long bytes = 0b11010010_01101001_10010100_10010010;
  
  System.out.println(creditCardNumber);
  System.out.println(bytes);
  
  System.out.println("Without underscores: ");
  
  creditCardNumber = 1234567890123456L;
  bytes = 0b11010010011010011001010010010010;
  
  System.out.println(creditCardNumber);
  System.out.println(bytes);
  
 }
}

Notice the underscores in the literals (e.g. 1234_5678_9012_3456L). Results written to the console:

With underscores: 
1234567890123456
-764832622
Without underscores: 
1234567890123456
-764832622

As you can see, the underscores do not make a difference to the values. They are just used to make the code more readible.

SafeVarargs

Pre-JDK 7, you always got an unchecked warning when calling certain varargs library methods. Without the new @SafeVarargs annotation this example would create unchecked warnings.

public class SafeVarargsExample {

 @SafeVarargs
 static void m(List... stringLists) {
  Object[] array = stringLists;
  List tmpList = Arrays.asList(42);
  array[0] = tmpList; // compiles without warnings
  String s = stringLists[0].get(0); // ClassCastException at runtime
 }

 public static void main(String[] args) {
  m(new ArrayList());
 }
 
}

The new annotation in line 3 does not help to get around the annoying ClassCastException at runtime. Also, it can only be applied to static and final methods. Therefore, I believe it will not be a great help. Future versions of Java will have compile time errors for unsafe code like the one in the example above.

Diamond

In Java 6 it required some patience to create, say, list of maps. Look at this example:


As you can see in the right part of the assignment in lines 3 and 4 you need to repeat your type information for the listOfMaps variable as well as of the aMap variable. This isn't necessary anymore in Java 7:


Multicatch

In Java 7 you do not need a catch clause for every single exception, you can catch multiple exceptions in one clause. You remember code like this:
public class HandleExceptionsJava6Example {
 public static void main(String[] args) {
  Class string;
  try {
   string = Class.forName("java.lang.String");
   string.getMethod("length").invoke("test");
  } catch (ClassNotFoundException e) {
   // do something
  } catch (IllegalAccessException e) {
   // do the same !!
  } catch (IllegalArgumentException e) {
   // do the same !!
  } catch (InvocationTargetException e) {
   // yeah, well, again: do the same!
  } catch (NoSuchMethodException e) {
   // ...
  } catch (SecurityException e) {
   // ...
  }
 }
}

Since Java 7 you can write it like this, which makes our lives a lot easier:

public class HandleExceptionsJava7ExampleMultiCatch {
 public static void main(String[] args) {
  try {
   Class string = Class.forName("java.lang.String");
   string.getMethod("length").invoke("test");
  } catch (ClassNotFoundException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) {
   // do something, and only write it once!!!
  }
 }
}

String in switch statements

Since Java 7 one can use string variables in switch clauses. Here is an example:

public class StringInSwitch {
 public void printMonth(String month) {
  switch (month) {
  case "April":
  case "June":
  case "September":
  case "November":
  case "January":
  case "March":
  case "May":
  case "July":
  case "August":
  case "December":
  default:
   System.out.println("done!");
  }
 }
}

Try-with-resource

This feature really helps in terms of reducing unexpected runtime execptions. In Java 7 you can use the so called try-with-resource clause that automatically closes all open resources if an exception occurs. Look at the example:

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

public class TryWithResourceExample {

 public static void main(String[] args) throws FileNotFoundException {
  
  // Java 7 try-with-resource
  
  String file1 = "TryWithResourceFile.out";
  try (OutputStream out = new FileOutputStream(file1)) {
   out.write("Some silly file content ...".getBytes());
   ":-p".charAt(3);
  } catch (StringIndexOutOfBoundsException | IOException e) {
   System.out.println("Exception on operating file " + file1 + ": " + e.getMessage());
  }
  
  // Java 6 style
  
  String file2 = "WithoutTryWithResource.out";
  OutputStream out = new FileOutputStream(file2);
  try {
   out.write("Some silly file content ...".getBytes());
   ":-p".charAt(3);
  } catch (StringIndexOutOfBoundsException | IOException e) {
   System.out.println("Exception on operating file " + file2 + ": " + e.getMessage());
  }

  // Let's try to operate on the resources
  
  File f1 = new File(file1);
  if (f1.delete())
   System.out.println("Successfully deleted: " + file1);
  else
   System.out.println("Problems deleting: " + file1);

  File f2 = new File(file2);
  if (f2.delete())
   System.out.println("Successfully deleted: " + file2);
  else
   System.out.println("Problems deleting: " + file2);
  
 }
}

In line 14 the try-with-resource clause is used to open a file that we want to operate on. Then line 16 generates a runtime exception. Notice that I do not explicitly close the resource. This is done automatically when you use try-with-resource. It *isn't* when you use the Java 6 equivalent shown in lines 21-30.

The code will write the following result to the console:

Exception on operating file TryWithResourceFile.out: String index out of range: 3
Exception on operating file WithoutTryWithResource.out: String index out of range: 3
Successfully deleted: TryWithResourceFile.out
Problems deleting: WithoutTryWithResource.out

That's it in terms of Project Coin. Very useful stuff in my eyes.

5 comments:

  1. very informative. Thanks for compiling and providing this list.

    ReplyDelete
  2. Well it work with Netbeans too? I guess i well find out my self!!!

    ReplyDelete
  3. Excellent compilation of examples. Thank you so much. :)

    ReplyDelete
  4. One thing which I don't like is the fact that you can't generate v6 bytecode with v7 sources, even though the implementation of the above features should work (as far as I can see) with the older bytecode. Ie. javac -source 1.7 -target 1.6 fails :-(

    ReplyDelete
  5. Indeed Project coin is good enhancement in programmers armory for day 2 day work, though not big as changes in Java5. Out of all features
    automatic resource management and fork join framework in java7 is my favorite with bit of interest on multiple catch block for exceptions. What I don't find much useful is diamond operator, why do you have it in place, it would have been better if compiler infer it from either side.

    ReplyDelete