Introduction

In July 2011, Java released its SDK version 7. This includes interesting features such as “Project NIO” (to produce the implementation of the New I/O APIs) and “Project Coin” (to determine what set of small language changes should be added to JDK 7)    

In this Article I’ve listed down selected five simple but effective features that have been added to Java language on its latest update.

  1. Strings in switch
  2. Binary integral literals and underscores in numeric literals
  3. Multi-catch and more precise rethrow
  4. Improved type inference for generic instance creation (diamond)
  5. try-with-resources statement 

 

Background

Supported Platforms: 

  • Microsoft Windows on x86 and x86-64
  • Oracle, Red Hat, SuSE and Ubuntu Linux on x86 and x86-64
  • Solaris on x86, x86-64 and SPARC

Supported IDEs: 

  • IntelliJ IDEA 10.5 and later
  • Eclipse 3.7.1 and later
  • NetBeans 7.0 and later 

Download Java SE Development Kit 7 here

 

Using the code 

1. Using Strings in switch  

The switch statement lets you evaluate a variable and then branch your code depending on the variable’s value. But up through Java 6, you could only evaluate primitive variables that are floats, longs, Booleans, integers, and so on. In Java7, you can use switch to evaluate a string.

 [box_light]

public String getTypeOfDayWithSwitchStatement(String dayOfWeekArg) {

     String typeOfDay;

     switch (dayOfWeekArg) {

         case “Monday”:

             typeOfDay = “Start of work week”;

             break;

         case “Tuesday”:

         case “Wednesday”:

         case “Thursday”:

             typeOfDay = “Midweek”;

             break;

         case “Friday”:

             typeOfDay = “End of work week”;

             break;

         case “Saturday”:

         case “Sunday”:

             typeOfDay = “Weekend”;

             break;

         default:

             throw new IllegalArgumentException(“Invalid day of the week: ” + dayOfWeekArg);

     }

     return typeOfDay;

[/box_light]

 

2) Binary integral literals and underscores in numeric literals

In Java SE 7, the integral types (byte, short, int, and long) can also be expressed using the binary number system. To specify a binary literal, add the prefix 0b or 0B to the number. The following examples show binary literals: 

 

[box_light]

// An 8-bit ‘byte’ value:

byte aByte = (byte)0b00100001;

 

// A 16-bit ‘short’ value:

short aShort = (short)0b1010000101000101;

 

// Some 32-bit ‘int’ values:

int anInt1 = 0b10100001010001011010000101000101;

int anInt2 = 0b101;

int anInt3 = 0B101; // The B can be upper or lower case.

 

// A 64-bit ‘long’ value. Note the “L” suffix:

long aLong = 0b1010000101000101101000010100010110100001010001011010000101000101L; 

[/box_light]

 

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

For instance, if your code contains numbers with many digits, you can use an underscore character to separate digits in groups of three, similar to how you would use a punctuation mark like a comma, or a space, as a separator. The following example shows other ways you can use the underscore in numeric literals: 

 

[box_light]

long creditCardNumber = 1234_5678_9012_3456L;

long socialSecurityNumber = 999_99_9999L;

float pi =       3.14_15F;

long hexBytes = 0xFF_EC_DE_5E;

long hexWords = 0xCAFE_BABE;

long maxLong = 0x7fff_ffff_ffff_ffffL;

byte nybbles = 0b0010_0101;

long bytes = 0b11010010_01101001_10010100_10010010; 

[/box_light]

 

3) Multi-catch and more precise rethrow 

In Java SE 7 and later, a single catch block can handle more than one type of exception. This feature can reduce code duplication and lessen the temptation to catch an overly broad exception. Consider the following example, which contains duplicate code in each of the catch blocks: 

 

[box_light]

catch (IOException ex) {

     logger.log(ex);

     throw ex;

catch (SQLException ex) {

     logger.log(ex);

     throw ex;

[/box_light]

 

In releases prior to Java SE 7, it is difficult to create a common method to eliminate the duplicated code because the variable ex has different types. The following example, which is valid in Java SE 7 and later, eliminates the duplicated code 

 

[box_light]

catch (IOException|SQLException ex) {

    logger.log(ex);

    throw ex;

[/box_light]

 

The catch clause specifies the types of exceptions that the block can handle, and each exception type is separated with a vertical bar (|).

Note: If a catch block handles more than one exception type then the catch parameter is implicitly final. In this example, the catch parameter ex is final and therefore you cannot assign any values to it within the catch block.

 

4) Improved type inference for generic instance creation (diamond) 

You can replace the type arguments required to invoke the constructor of a generic class with an empty set of type parameters (<>) as long as the compiler can infer the type arguments from the context. This pair of angle brackets is informally called the diamond. For example, consider the following variable declaration:  

[box_light]Map<String, List<String>> myMap = new HashMap<String, List<String>>(); [/box_light]

In Java SE 7, you can substitute the parameterized type of the constructor with an empty set of type parameters (<>): 

[box_light]Map<String, List<String>> myMap = new HashMap<>() [/box_light]

Note that to take advantage of automatic type inference during generic class instantiation, you must specify the diamond. In the following example, the compiler generates an unchecked conversion warning because the HashMap() constructor refers to the HashMap raw type, not the Map<String, List<String>> type: 

[box_light]Map<String, List<String>> myMap = new HashMap(); // unchecked conversion warning [/box_light]

 

5) try-with-resources statement 

The try-with-resources statement is a try statement that declares one or more resources. A resource is as an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement.

Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource. The following example reads the first line from a file. It uses an instance of BufferedReader to read data from the file. BufferedReader is a resource that must be closed after the program is finished with it: 

 

[box_light]

static String readFirstLineFromFile(String path) throws IOException {

  try (BufferedReader br = new BufferedReader(new FileReader(path))) {

    return br.readLine();

  }

}<span style=”font-size: 14px; white-space: normal;”>

</span>

[/box_light]

 

In this example, the resource declared in the try-with-resources statement is a BufferedReader. The declaration statement appears within parentheses immediately after the try keyword. The class BufferedReader, in Java SE 7 and later, implements the interface java.lang.AutoCloseable. Because the BufferedReader instance is declared in a try-with-resource statement, it will be closed regardless of whether the try statement completes normally or abruptly (as a result of the method BufferedReader.readLine throwing an IOException).

Prior to Java SE 7, you can use a finally block to ensure that a resource is closed regardless of whether the try statement completes normally or abruptly. The following example uses a finally block instead of a try-with-resources statement: 

 

[box_light]

static String readFirstLineFromFileWithFinallyBlock(String path) throws IOException {

  BufferedReader br = new BufferedReader(new FileReader(path));

  try {

    return br.readLine();

  } finally {

    if (br != null) br.close();

  }

[/box_light]

 

Points of Interest

A quick look at the Project NIO:

In Java 7 there’s a new system for working with directories and files. The classes that are a part of the system are part of a package called Java.nio, for new input-output. The core of this new system is a class called path that replaces the old file class.

New I/O, usually called NIO, is a collection of Java programming language APIs that offer features for intensive I/O operations. The APIs of NIO were designed to provide access to the low-level I/O operations of modern operating systems The Java NIO APIs are provided in the java.nio package and its sub packages. The documentation by Oracle identifies these key features:

  • Buffers for data of primitive types
  • Character set encoders and decoders
  • A pattern-matching facility based on Perl-style regular expressions 
  • Channels, a new primitive I/O abstraction
  • A file interface that supports locks and memory mapping
  • A multiplexed, non-blocking I/O facility for writing scalable servers 

History

Java Version History

  • JDK 1.0 (January 21, 1996)         
  • JDK 1.1 (February 19, 1997)
  • J2SE 1.2 (December 8, 1998)
  • J2SE 1.3 (May 8, 2000)
  • J2SE 1.4 (February 6, 2002)
  • J2SE 5.0 (September 30, 2004)
  • Java SE 6 (December 11, 2006)
  • Java SE 7 (July 28, 2011) 

4 COMMENTS

  1. Really a nice document which is much more informative and having a vivid imagination of flow of data which is going to from one point to another for a expected command using RSS and making a note.

  2. Thanks for the post you have made Mr Krishan Senevirathne, I can remember we discussed in the OCJP session regarding new features, slight development effort required to get adopted into

LEAVE A REPLY

Please enter your comment!
Please enter your name here