Following are some of the cool features introduced on Java 7.
equals() and hashcode() method from java.lang.String is used in comparison, which is case-sensitive. Benefit of using String in switch is that, Java compiler can generate more efficient code than using nested if-then-else statement.
For example, consider the following variable declaration:
In Java SE 7, you can substitute the parameterized type of the constructor with an empty set of type parameters (<>):
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:
For example, before JDK 7, you need two catch blocks to catch two exception types although both perform identical task:
In JDK 7, you could use one single catch block, with exception types separated by '|'.
By the way, just remember that Alternatives in a multi-catch statement cannot be related by sub classing. For example a multi-catch statement like below will throw compile time error :
Alternatives in a multi-catch statement cannot be related by sub classing, it will throw error at compile time :
The try-with-resources statement is a try statement that declares one or more resources. A resource is 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:
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).
Following additional features have been introduced in NIO package.
Anyhow it would be recommended to check Java doc of new file package to learn more about this interesting useful feature.
1. Strings in switch Statement
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");
}
equals() and hashcode() method from java.lang.String is used in comparison, which is case-sensitive. Benefit of using String in switch is that, Java compiler can generate more efficient code than using nested if-then-else statement.
2. Type Inference for Generic Instance Creation (Diamond Operator)
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:
Map<String, List<String>> myMap = new HashMap<String, List<String>>();
In Java SE 7, you can substitute the parameterized type of the constructor with an empty set of type parameters (<>):
Map<String, List<String>> myMap = new HashMap<>();
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:
Map<String, List<String>> myMap = new HashMap(); // unchecked conversion warning
3. Multiple Exception Handling
In JDK 7, a single catch block can handle more than one exception types.For example, before JDK 7, you need two catch blocks to catch two exception types although both perform identical task:
try {
......
} catch(ClassNotFoundException ex) {
ex.printStackTrace();
} catch(SQLException ex) {
ex.printStackTrace();
}
In JDK 7, you could use one single catch block, with exception types separated by '|'.
try {
......
} catch(ClassNotFoundException|SQLException ex) {
ex.printStackTrace();
}
By the way, just remember that Alternatives in a multi-catch statement cannot be related by sub classing. For example a multi-catch statement like below will throw compile time error :
try {
......
} catch (FileNotFoundException | IOException ex) {
ex.printStackTrace();
}
Alternatives in a multi-catch statement cannot be related by sub classing, it will throw error at compile time :
java.io.FileNotFoundException is a subclass of alternative java.io.IOException
at Test.main(Test.java:18)
4. Binary Literals, underscore in literals
In JDK 7, you could insert underscore(s) '_' in between the digits in an numeric literals (integral and floating-point literals) to improve readability. This is especially valuable for people who uses large numbers in source files, may be useful in finance and computing domains. For example,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;
5. 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 betterint binary = 0B0101_0000_1010_0010_1101_0000_1010_0010;
6. The try-with-resources Statement
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:static String readFirstLineFromFileWithFinallyBlock(String path)
throws IOException {
BufferedReader br = new BufferedReader(new FileReader(path));
try {
return br.readLine();
} finally {
if (br != null) br.close();
}
}
The try-with-resources statement is a try statement that declares one or more resources. A resource is 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:
static String readFirstLineFromFile(String path) throws IOException {
try (BufferedReader br =
new BufferedReader(new FileReader(path))) {
return br.readLine();
}
}
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).
7. 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.Following additional features have been introduced in NIO package.
- 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.
Anyhow it would be recommended to check Java doc of new file package to learn more about this interesting useful feature.
No comments:
Post a Comment