Java 5 Features

Naveen AnamaneniUpdated · 5 min read

Some school buildings get a fresh coat of paint every year, and once in a long while they get a whole new wing. Java 5, released in September 2004, was a new wing. It changed how everyday Java code looks more than any release before Java 8: almost every program you write today uses at least three of its features. In this lesson, you will get a quick reference to everything Java 5 added, see old-style and Java 5 code side by side, and find the lesson that covers each feature in depth.

What Did Java 5 Add?

Java 5 (also called J2SE 5.0, code name "Tiger") is the Java release that added generics, annotations, autoboxing, enums, varargs, the enhanced for loop and static import to the language, and the java.util.concurrent package to the library. Its version number was the first to drop the "1." in marketing (internally it was 1.5).

Language Features

FeatureWhat it gives youRead more
GenericsType-safe collections and methods: List<String> instead of a raw List and casts"Generics in Java"
Enhanced for loopfor (String name : names) without an index or iterator"Java For-Each Loop"
Autoboxing and unboxingAutomatic conversion between int and Integer"Autoboxing and Unboxing in Java"
EnumsType-safe constants with fields and methods: enum Grade { A, B, C }"Enums in Java"
VarargsMethods that take any number of arguments: sum(int... values)"Varargs (Variable Arguments)"
Static importUse static members without the class name: import static java.lang.Math.max;"Static Import in Java"
AnnotationsMetadata on code: @Override, @Deprecated, @SuppressWarnings, and your own"Annotations in Java"
Covariant return typesAn overriding method can return a subtype"Covariant Return Type in Java"

Library Features

FeatureWhat it gives youRead more
java.util.concurrentExecutors, thread pools, ConcurrentHashMap, locks, atomics, CountDownLatch"Executor Framework in Java"
StringBuilderA faster, unsynchronized StringBuffer"StringBuilder in Java"
ScannerEasy reading of numbers and words from input"Scanner Class"
printf and String.formatC-style formatted output"PrintStream and PrintWriter in Java"
Queue interface and PriorityQueueStandard queues in the collections framework"Queue Interface and PriorityQueue in Java"

Before and After Java 5

Let's see a small program written the Java 5 way, with the pre-Java 5 version of each line in a comment.

Tiger.java▶ Try it
import static java.lang.Math.max;
 
import java.util.ArrayList;
import java.util.List;
 
public class Tiger {
    enum Grade { A, B, C }                           // was: static final ints
 
    static int best(int... marks) {                  // was: best(int[] marks)
        int top = 0;
        for (int m : marks) {                        // was: index loop
            top = max(top, m);                       // was: Math.max(...)
        }
        return top;
    }
 
    @Override                                        // was: no checking
    public String toString() {
        return "Tiger";
    }
 
    public static void main(String[] args) {
        List<Integer> marks = new ArrayList<Integer>();  // was: raw List
        marks.add(91);                               // was: new Integer(91)
        marks.add(78);
        int first = marks.get(0);                    // was: cast + intValue()
 
        System.out.println("first: " + first);
        System.out.println("best: " + best(91, 78, 85));
        System.out.printf("grade for %s: %s%n", "Navika", Grade.A);
        System.out.println(new Tiger());
    }
}
Output
first: 91
best: 91
grade for Navika: A
Tiger

Explanation:

  1. List<Integer> tells the compiler what the list holds, so marks.get(0) needs no cast. Before Java 5, every get returned Object.
  2. marks.add(91) autoboxes the int into an Integer, and int first = marks.get(0) unboxes it.
  3. int... marks lets callers pass any number of values, and the for-each loop reads them without an index.
  4. enum Grade replaces groups of static final int constants that the compiler couldn't check.
  5. printf formats output with placeholders. Note that new ArrayList<Integer>() is the Java 5 spelling; since Java 7 you can write new ArrayList<>().

Java 6 in One Paragraph

Java 6 (December 2006) was mostly about performance and tools rather than language changes. It added the scripting API (javax.script), the compiler API (javax.tools), JDBC 4.0 (drivers load automatically, no more Class.forName), and allowed @Override on methods that implement an interface. Most programmers remember it for being fast and stable.

Practice

  1. Easy: Rewrite this pre-Java 5 line in modern style: List names = new ArrayList(); names.add("Srihitha"); String s = (String) names.get(0);
  2. Harder: From memory, write one line of code for each of the seven Java 5 language features in the first table. Compile them all in one class.

Quick check: Java 5

4 questions
1Which feature did Java 5 add?
2What does autoboxing do?
3Which package did Java 5 add for concurrency?
4Which syntax is varargs?

Key Takeaways

Was this tutorial helpful?

Lesson 559 of 578