1) Type inference
Prior JDK 7
Map<String, List<String>> employeeRecords = new HashMap<String, List<String>>();
List<Integer> primes = new ArrayList<Integer>();
In JDK 7Map<String, List<String>> employeeRecords = new HashMap<>();
List<Integer> primes = new ArrayList<>();
2) String in Switch
Before JDK 7, only integral types can be used as selector for switch-case statement. In JDK 7, you can use a String object as the selector. For example,
String state = "NEW";
switch (day) {
case "NEW": System.out.println("Order is in NEW state"); break;
case "CANCELED": System.out.println("Order is Cancelled"); break;
case "REPLACE": System.out.println("Order is replaced successfully"); break;
case "FILLED": System.out.println("Order is filled"); break;
default: System.out.println("Invalid");
}
3) Automatic Resource Management
Before JDK 7, we need to use a finally block, to ensure that a resource is closed regardless of whether the try statement completes normally or abruptly, for example while reading files and streams, we need to close them into finally block, which result in lots of boiler plate and messy code, as shown below :
public static void main(String args[]) {
FileInputStream fin = null;
BufferedReader br = null;
try {
fin = new FileInputStream("info.xml");
br = new BufferedReader(new InputStreamReader(fin));
if (br.ready()) {
String line1 = br.readLine();
System.out.println(line1);
}
} catch (FileNotFoundException ex) {
System.out.println("Info.xml is not found");
} catch (IOException ex) {
System.out.println("Can't read the file");
} finally {
try {
if (fin != null) fin.close();
if (br != null) br.close();
} catch (IOException ie) {
System.out.println("Failed to close files");
}
}
}
Look at this code, how many lines of boiler codes?Now in Java 7, you can use try-with-resource feature to automatically close resources, which implements AutoClosable and Closeable interface e.g. Streams, Files, Socket handles, database connections etc. JDK 7 introduces a try-with-resources statement, which ensures that each of the resources in try(resources) is closed at the end of the statement by calling close() method of AutoClosable. Now same example in Java 7 will look like below, a much concise and cleaner code :
public static void main(String args[]) {
try (FileInputStream fin = new FileInputStream("info.xml");
BufferedReader br = new BufferedReader(new InputStreamReader(fin));) {
if (br.ready()) {
String line1 = br.readLine();
System.out.println(line1);
}
} catch (FileNotFoundException ex) {
System.out.println("Info.xml is not found");
} catch (IOException ex) {
System.out.println("Can't read the file");
}
}
4) Fork Join Framework
5) Underscore in Numeric literals
int billion = 1_000_000_000;
// 10^9
long creditCardNumber = 1234_4567_8901_2345L;
//16 digit number long ssn = 777_99_8888L;
double pi = 3.1415_9265;
float pif = 3.14_15_92_65f;
6) Catching Multiple Exception Type in Single Catch Block
try { ......
} catch(ClassNotFoundException ex) {
ex.printStackTrace();
} catch(SQLException ex) {
ex.printStackTrace();
}
try {
......
} catch (FileNotFoundException | IOException ex) {
ex.printStackTrace();
}
7) Binary Literals with prefix "0b"
In JDK 7, you can express literal values in binary with prefix '0b' (or '0B') for integral types (byte, short, int and long), similar to C/C++ language. Before JDK 7, you can only use octal values (with prefix '0') or hexadecimal values (with prefix '0x' or '0X').
int mask = 0b01010000101;
or even better
int binary = 0B0101_0000_1010_0010_1101_0000_1010_0010;
8) Java NIO 2.0
Java SE 7 introduced java.nio.file package and its related package, java.nio.file.attribute, provide comprehensive support for file I/O and for accessing the default file system. It also introduced the Path class which allow you to represent any path in operating system. New File system API complements older one and provides several useful method checking, deleting, copying, and moving files. for example, now you can check if a file is hidden in Java. You can also create symbolic and hard links from Java code. JDK 7 new file API is also capable of searching for files using wild cards. You also get support to watch a directory for changes. I would recommend to check Java doc of new file package to learn more about this interesting useful feature.
9) G1 Garbage Collector
JDK 7 introduced a new Garbage Collector known as G1 Garbage Collection, which is short form of garbage first. G1 garbage collector performs clean-up where there is most garbage. To achieve this it split Java heap memory into multiple regions as opposed to 3 regions in the prior to Java 7 version (new, old and permgen space). It's said that G1 is quite predictable and provides greater through put for memory intensive applications.
10) More Precise Rethrowing of Exception
public void obscure() throws Exception{
try {
new FileInputStream("abc.txt").read();
new SimpleDateFormat("ddMMyyyy").parse("12-03-2014");
} catch (Exception ex) {
System.out.println("Caught exception: " + ex.getMessage());
throw ex;
}
}
=====
public void precise() throws ParseException, IOException {
try {
new FileInputStream("abc.txt").read();
new SimpleDateFormat("ddMMyyyy").parse("12-03-2014");
} catch (Exception ex) {
System.out.println("Caught exception: " + ex.getMessage());
throw ex;
}
}
The Java SE 7 compiler allows you to specify the exception types ParseException and IOException in the throws clause in the preciese() method declaration because you can re-throw an exception that is a super-type of any of the types declared in the throws, we are throwing java.lang.Exception, which is super class of all checked Exception. Also in some places you will see final keyword with catch parameter, but that is not mandatory any more.