Java 7 New Features

As with every new Java version, Java 7 introduced some new features. The new features are definitely worth the change and as developers, we must be happy as we can be more efficient. There are many features introduced in Java 7 but we will look at some of them.

Allows Strings to be used in ‘case’ switch statements.

Try with resources

Custom Autocloseable Class

Using underscore characters in numeric values.

Multi-catch Exceptions

Improved Type reference for Generic Instance creation

Binary literals

Lets look at these features one by one.

Strings In Switch Statements

In all computer languages that I know of, switch case statements can switch either on int or char type. If at all, we needed to switch based on Strings, then we had to figure out some workarounds using char data types or else switch to “if-else” logic to do that. And Java allowed ‘enum’ types also to be used in switch statement. But still we were not able to switch based on strings in switch case statements till Java 7.

Java 7 officially supports using Strings in switch case statements. This can definitely save developers some time instead of opting for workarounds. A good research topic would be trying to figure out the reasons Java took so long for Strings to be included in switch case statements!. An example is illustrated below: (this code will not compile in any version below Java 7)

This program is pretty straightforward to understand. It reads from a file line by line and prints out the content. The class FileReader throws IOException and the BufferedReader class throws a checked IOException. Since these are checked exceptions, I am surrounding this piece of code in a try-catch block. And at last, I need to close the opened resources and so use br.close() in the finally block to close the file. This finally block will be called regardless of an exception occurs or not. And then again in the finally block, since br.close() throws a checked exception, that is also surrounded with try-catch block.

Think of a scenario where there are 10 checked exceptions that need to be handled. Either we can throw them to the parent class and catch them all under the parent java.io.Exception class. But applications needs sophisticated error messages to be displayed and so we need to handle each exception differently. So we will have 10 try-catch blocks, and one finally block to clean up all resources. Again, we may have several try-catch blocks inside finally block as it may throw some checked exceptions just like shown in our example.

Do you get an idea of the volume of code in catch block first and then almost similar exceptions being handled in finally block while cleaning up opened resources. Wouldn’t it be if Java made it simpler to code?. Yes. Java 7 does this exactly and it is called Try-with-Resources statement. This is how it works.

Almost 5-6 lines of code has been coded in just one line of code. This method of handling the cleanup of resources using only “try” statement is called Try-With-Resources statement. But then are we missing something? You may ask where is the br.close() method!. In our example, the FileReader and BufferedReader classes implement java.lang.AutoCloseable interface, which takes care of closing these resources. I will also provide an example of this AutoCloseable interface in this article. Also, multiple try-with resources can be used by separating them with a semi-colon; eg.,

If you are wondering in which order these resources will be closed. Javadocs has an answer. It will be closed in the opposite order it appears in the Try-With-resources statement. So, in our case first buff.close() will be called and then fRead.close() will be called. Also, what about the exceptions handling. Though the fRead.close() and buff.close() methods implements AutoCloseable interface, exceptions in the try block exceptions take preference over the close() exceptions. In other words, if exceptions occur in try-with-resources statement and close() method, only the try-with-resource exception will be passed back to the stack and the close() methods exception will be suppressed. Also if needed, there are methods to get this suppressed exception also. So the try-with-resources exception take precedence over exceptions in AutoCloseable interface.

Custom AutoCloseable Class

I will provide an example, which extends this AutoCloseable interface so that we can use it if required in our own classes.

Underscore Character In Numeric Values

This was introduced to improve the code readability. Underscores can be used wherever we use numeric values. Assume that you want to declare a number i.e., say 1 million, prior to Java 7, declaration would be something like this:

int million = 1000000;

This may be hard to read, as the user may have to manually count the zeros and then figure out that if it is 1 million/10 million. Wouldn’t it be nice if we are allowed to declare as 1,000,000 clearly separating 1 million from 10 million using commas just as we do in Maths. Wouldn’t it improve code readability?

Exactly. This is what Java 7 address. Instead of comma, we are allowed to use underscore character (_) between numeric values.

int million = 1_000_000;
double amount = 60.50_40_30;

Though there are certain rules that must be kept in mind, that is a _ can’t begin a numeral, a _ can’t precede/succeed a decimal point, it helps developers make the code readable.

int million = _100; // invalid
double amount = 60._50; // invalid

Multi-Catch Exceptions

Lets look at the next feature – multi –catch exceptions. Before Java 7, we needed to have catch block for each of the different exceptions that needed to be handled.

Renga is currently working as a software engineer. He has experience developing web applications using spring, struts and Hibernate framework. He is passionate about learning new technologies and has recently started writing a blog http://renga86.blogspot.com mainly focussing on Java.

15 Responses to "Java 7 New Features"

// If I write separate then file instance is not auto closable, Could you explain how it works internally. try( File f=new File(“”); FileInputStream fis=new FileInputStream(f); BufferedInputStream bis=new BufferedInputStream(fis) ){

Thanks Siddu. Ya you are right … If the parent class Exception exists, then we can’t include the child class Exception in the multi try-catch block … i wanted to have some other exception but in my attempt to give the same example as in Java 6, I didn’t notice this … will change it …

siddu, AutoCloseable is only applicable for resources which needs to be closed after they are opened for IO. In case of File, we are not opening/closing a resource but just checking if the file exists in that path or not. Only when using FileReader or FileInputStream, you start reading that file line by line/character by character and stuff like that … That is why, if u check Java Docs java.io.File doesn’t implement AutoCloseable interface but rather FileReader and BufferedReader does … so this will work because try-with-resources should contain only classes implementing AutoCloseable …

try( FileInputStream fIn = new FileInputStream(new File(“f”)); BufferedInputStream bIn = new BufferedInputStream(fIn)) { } catch (Exception e) { e.printStackTrace(); } to understand better, check all the API under File and u will find only APIs which check for file exists, path valid and not for reading from the file … hope this clarifies your question …

} catch (FileNotFoundException | IOException e) { // This snippet is wrong. Since FileNFE is suclass of IOE. So it wont allows subtypes here. We can only assign different type. IOE is the one handles FNFE as well as IOE so thats why it wont support both.

Thanks Siddu. Ya you are right … If the parent class Exception exists, then we can’t include the child class Exception in the multi try-catch block … i wanted to have some other exception but in my attempt to give the same example as in Java 6, I didn’t notice this … will change it …

if you are referring to Improved Type reference For Generic Instance section, ArrayList string = new ArrayList(), that is a typo and is has been already changed. probably might take some time to get reflected.

this is what i meant: ArrayList listStr = new ArrayList(); /// before java 7 After Java 7, ArrayList listStr = new ArrayList();

i didn’t quite get your question, can you please make it a little clear…

still all your lines of code look the same … sorry, i don’t see any difference in ur code snippet… but you are saying it makes “type safety” which might be incorrect. suppose you have ArrayList list2 = new ArrayList(); this declaration doesn’t stop you from loading all types of objects : strings, double, Integer … suppose you want to get all the elements, how will you retrieve this heterogenous data? its all mixed data … so always use parameterized like ArrayList lsit2 = new ArrayList() so that user/anyone who looks at the code knows this list can store only string items …

Why constructor name is same as class name? any technical reason. why there is only one public class per source code in java why hashmap allows null key and values & not by hashtable? How to use user defined objects as key for hashmap. Could you give one example. Why key objects should be immutable? Whats the benefits?