Java 7 Features

Naveen AnamaneniUpdated · 5 min read

Small improvements to a school day can matter more than big ones: a door that closes by itself, a register that fills in the date automatically, a corridor sign that is finally easy to read. Java 7, released in July 2011 after a five-year wait, was a release of exactly those small, practical fixes. Its features (collected under the name "Project Coin") removed boilerplate that Java programmers had been typing for years. In this lesson, you will get a quick reference to what Java 7 added, see the before and after in code, and find the lesson that covers each feature.

What Did Java 7 Add?

Java 7 is the Java release that added try-with-resources, multi-catch, the diamond operator, strings in switch, binary literals and underscores in numbers to the language, and NIO.2 (Path, Files), the fork/join framework and the Objects utility class to the library. It was the first release under Oracle, which had bought Sun Microsystems in 2010.

Language Features

FeatureWhat it gives youRead more
Try-with-resourcesFiles, connections and streams close automatically, even after an exception"Try-With-Resources in Java"
Multi-catchcatch (IOException | SQLException e) handles several exceptions in one block"Multiple Catch Blocks and Multi-Catch"
Diamond operatornew ArrayList<>(): the compiler works out the type arguments"Diamond Operator in Java"
Strings in switchswitch (day) { case "MON": ... }"Switch Statement"
Binary literals0b1010 for the number 10"Literals in Java"
Underscores in numbers1_000_000 instead of 1000000"Literals in Java"
More precise rethrowRethrowing a caught Exception keeps the specific checked types"Try-Catch Block in Java"

Library and JVM Features

FeatureWhat it gives youRead more
NIO.2: Path, Paths, FilesA modern file API: copy, move, walk folders, read all lines"NIO.2 Path and Files Classes"
Fork/join frameworkSplit work across CPU cores with ForkJoinPool and RecursiveTask"Fork/Join Framework in Java"
java.util.Objectsequals, hash, requireNonNull, toString helpers that handle null"Objects Utility Class in Java"
AutoCloseableThe interface behind try-with-resources"Try-With-Resources in Java"
invokedynamicA new bytecode instruction, later used to implement lambdas in Java 8"How Lambdas Are Compiled"

Before and After Java 7

Let's see a program that uses most of the Java 7 additions together.

Coin.java▶ Try it
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
 
public class Coin {
    static String dayType(String day) {
        switch (day) {                                   // strings in switch
            case "SAT":
            case "SUN":
                return "holiday";
            default:
                return "school day";
        }
    }
 
    public static void main(String[] args) throws IOException {
        List<String> names = new ArrayList<>();          // diamond
        names.add("Navika");
        names.add("Advitha");
 
        int fee = 1_50_000;                              // underscores
        int flags = 0b0101;                              // binary literal
        System.out.println("fee " + fee + ", flags " + flags);
        System.out.println("MON is a " + dayType("MON"));
 
        Path file = Files.createTempFile("roll", ".txt"); // NIO.2
        Files.write(file, names);
        try (var lines = Files.lines(file)) {            // try-with-resources
            lines.forEach(n -> System.out.println("read " + n));
        }
        Files.delete(file);
 
        try {
            Object o = names.get(5);
        } catch (IndexOutOfBoundsException | NullPointerException e) {
            System.out.println("multi-catch caught "    // multi-catch
                    + e.getClass().getSimpleName());
        }
        System.out.println(Objects.equals(null, null));  // Objects helper
    }
}
Output
fee 150000, flags 5
MON is a school day
read Navika
read Advitha
multi-catch caught IndexOutOfBoundsException
true

Explanation:

  1. new ArrayList<>() saves repeating <String>.
  2. 1_50_000 groups digits the Indian way (one lakh fifty thousand); the underscores are ignored by the compiler. 0b0101 is 5.
  3. Files.write and Files.lines read and write a whole file in one call. The try (...) block closes the stream automatically. (var and the lambda come from later releases; in Java 7 you would write the full type and a loop.)
  4. Multi-catch handles two exception types in one catch block.
  5. Objects.equals(null, null) returns true instead of throwing a NullPointerException.

Practice

  1. Easy: Rewrite this with Java 7 features: Map<String, List<Integer>> marks = new HashMap<String, List<Integer>>(); int crore = 10000000;
  2. Harder: Write a method that copies a text file with Files.copy, catches NoSuchFileException | AccessDeniedException in one block, and uses try-with-resources to read the copied file's first line with a BufferedReader.

Quick check: Java 7

4 questions
1Which Java 7 feature closes resources automatically?
2What does new ArrayList<>() rely on?
3Which number literal is valid since Java 7?
4Which classes form NIO.2?

Key Takeaways

Was this tutorial helpful?

Lesson 560 of 578