Chapter 4. Java 5.0 Language Features

This chapter covers the three most important new language features of Java 5.0. Generics add type-safety and expressiveness to Java programs by allowing types to be parameterized with other types. A List that contains String objects, for example, can be written as List<String> . Using parameterized types makes Java code clearer and allows us to remove most casts from our programs.

Enumerated types, or enums, are a new category of reference type, like classes and interfaces. An enumerated type defines a finite (“enumerated”) set of values, and, importantly, provides type-safety: a variable of enumerated type can hold only values of that enumerated type or null. Here is a simple enumerated type definition:

public enum Seasons { WINTER, SPRING, SUMMER, AUTUMN }

The third Java 5.0 feature discussed in this chapter is program annotations and the annotation types that define them. An annotation associates arbitrary data (or metadata) with a program element such as a class, method, field, or even a method parameter or local variable. The type of data held in an annotation is defined by its annotation type, which, like enumerated types, is another new category of reference type. The Java 5.0 platform includes three standard annotation types used to provide additional information to the Java compiler. Annotations will probably find their greatest use with code generation tools in Java enterprise programming.

Java 5.0 also introduces a number of other important new language features that don’t require a special chapter to explain. Coverage of these changes is found in sections throughout Chapter 2. They include:

  • Autoboxing and unboxing conversions

  • The for/in looping statement, sometimes called “foreach”

  • Methods with variable-length argument lists, also known as varargs methods

  • The ability to narrow the return type of a method when overriding, known as a " covariant return”

  • The import static directive, which imports the static members of a type into the namespace

Get Java in a Nutshell, 5th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.