Saturday, May 24, 2014

New Features of Java 7

Java 7 contains many new features, enhancements and bug fixes to improve efficiency to develop and run Java programs.

Here is a brief summary of the enhancements included with the Java 7 release:

  • Improved performance, stability and security.
  • Enhancements in the Java Plug-in for Rich Internet Applications development and deployment.
  • Java Programming language enhancements that enable developers with ease of writing and optimizing the Java code.
  • Enhancements in the Java Virtual machine to support Non-Java languages.

In this article, we will explore some of those capabilities through code samples.

1. Binary literals

You can use the binary number system (0s and 1s) to express integral types byte, short, int, and long. To specify a binary value, prefix the value with a 0b or 0B.


--------------------- Output ---------------------
a = -88
b = 112
c = 73
d = 1467

2. Underscore literals

To improve readability of numeric literals in the code, you can use underscores between digits to separate a group of digits. You can use as many underscores as you need.


--------------------- Output ---------------------
a = -86
b = 4554
c = 123456789
d = 111222333
e = 11.227799


3. Diamond operator

Now you can save few more key strokes by using diamond(<>) operator. Empty type parameter <> can be used to invoke the constructor of a generic class, java compiler will infer the type arguments from the context.


--------------------- Output ---------------------
[john, ron, paul]

4. String in switch condition

In earlier version of java, switch used to support char, byte, int, short and enum only however now with the Java 7 you can provide String object in a switch condition. The switch statement compares the String object from its expression with each of the case values using the String.equals() method.


--------------------- Output ---------------------
Today is Friday

5. Try with resources

In the earlier versions of Java, if you had to work with file, network or database resources, you would open the resource within the try block, handle any exceptions in the catch block and close the resource in the finally block.


With the introduction of try-with-resources statement in Java 7, the try statement declares one or more resource(s). The try-with-resources statement ensures that each of the resource(s) is closed at the end of the statement. It also results in elegant code.

6. Catching Multiple Exception

In the earlier versions of Java, you would have multiple catch blocks to handle the different types of exceptions thorwn from the try block.


In Java 7, a single catch statement can be used to handle different type of exceptions.