Following are the features that are very useful JDK 1.7
1.
Strings
in switch Statements : We can start
using Strings in switch case statements:
String option;
switch(option)
{
case “start”:
System.out.println(“Starting
the process”);
…….
break;
case “pause”:
System.out.println(“Pausing the process”);
break;
case “stop”:
System.out.println(“Stopping the process”);
break;
default:
System.out.println(“continue”);
break;
}
2. Catching Multiple Exception Types and Rethrowing Exceptions with Improved Type Checking : We would have been using multiple catch blocks doing the same thing. Below is an example where this can be used
Pre JDK 1.7
|
JDK 1.7
|
try
{
….
}catch(FileNotFoundException fe)
{
log.error(“---EXCEPTION
occurred with file handling-- ”+ fe.getMessage());
throw
new CustomException(fe);
}catch(IOException ie)
{
log.error(“---EXCEPTION
occurred with file handling-- ”+ ie.getMessage());
throw
new CustomException(Ie);
}catch(Exception e)
{
log.error(“---EXCEPTION
occurred with file handling-- ”+ e.getMessage());
throw
new CustomException(e);
}
|
try
{
}catch(FileNotFoundException
| IOException | Exception e)
{
log.error(“---EXCEPTION occurred
with file handling-- ”+ e.getMessage());
throw
new CustomException(e);
}
|
3. The
try-with-resources Statement : We can open Autoclosable resources like Streams, JDBC connection,
Statements, Resultset within the try.
The resources will be automatically closed when the try ends.
Pre JDK 1.7
|
JDK 1.7 (resources are auto-closed after the try statement)
|
BufferedReader
breader = new BufferedReader(new FileReader(path));
FileOutputStream
fs = new FileOutputStream(new File (…));
try {
…
…
}
finally {
if (breader != null)
breader.close();
if (os != null)
os.close();
}
|
try(BufferedReader breader = new BufferedReader(new
FileReader(path));
FileOutputStream fs = new FileOutputStream(new
File (…))
){
………………….
}catch(..){
….
}
|
4. Automatic
Type inference : Easy Type declaration. This will not work when declaring
Generics with wildcard.
Pre JDK 1.7
|
JDK 1.7 :
Easy declaration with “diamond Operator”
|
List<String> listNames = new
ArrayList<String>();
Map<String, Integer> mapStrNumbers
= new HashMap<String, Integer>();
|
List<String> listNames = new ArrayList<>();
Map<String, Integer> mapStrNumbers
= new HashMap<>();
|