Next page | Contents page |

More new things from Java 5

Static imports

To avoid repeatedly using the name of a class in front of static fields or methods. Eg,

	import static java.lang.Math;

allows you to write sin (PI) rather than Math.sin (Math.PI). Useful for class Math and certain other ones but use sparingly otherwise - can be confusing.

Variable number of arguments

Before Java 5 it was only possible to have a variable number of arguments for a method by collecting values in an array or list. Now we have an alternative:

	public void sendInvoices (Customer... c);

declares a method with a variable number of arguments. The ... can only be used on the last argument of a method. Overloading should be avoided. A for-each loop can be used inside the method to get each parameter c.

This has also made possible a new C-like printf () method in java.io.PrintWriter and java.io.PrintStream (eg, for System.out) which can make formatted output easier. See the API documentation for details.

Auto-boxing & unboxing

Using primitive types in java.util.Collections is impossible. You have to construct an object of the class corresponding to the primitive type. So another innovation is to hide the details and let the compiler do it:

	List<Integer> a = new ArrayList<Integer> ();
	a.add (42); // No need to construct an Integer object
	int i = a.get (0);// No need to cast and call intValue ()

NB: It is not a good idea to use this in intensive numerical calculations because of performance. Also beware that an Integer could be null. Unboxing that would cause a NullPointerException.

Next page | Contents page |