New syntax features of Java 7:
Preface: This is a majority of features, but some are not written into it. For example, the support for multi-core parallel computing and the fork join framework are enhanced. This will not be written in.
1. Added support for the String type in the switch.
Java code
Public String generate (String name, String gender) {String title = "\"; switch (gender) {case "male": title = name + ""; break; case "": title = name + ""; break; default: title = name;} return title;
The compiler must handle the following during compilation:
① There is only one case in case, which is directly converted into if;
② If there is only one case and default, it is directly converted to if... else ...;
③ There are multiple cases. First, convert the String to hashCode and then process the corresponding case. JavaCode is compatible with Java 7 and earlier versions at the underlying layer.
2. Improvement on the number literal volume
① Add binary representation
Before Java 7, it supports decimal (123), octal (0123), and hexadecimal (0X12AB)
Add binary representation in Java 7 (0B11110001 and 0b11110001)
② Separators can be added to numbers
In Java 7, you can add '_' in the middle of a number as a separator, which is more intuitive. For example (12_123_456), the underline can only be in the middle of a number. during compilation, the compiler automatically deletes the underline in the number.
3. Exception Handling
① The Throwable class adds the addSuppressed method and the getSuppressed method, and supports adding the restrained exception to the original exception.
Exception suppression: When both try and finally throws an exception, the exception thrown in finally is passed up in the exception stack, and the original exception generated in try disappears.
In versions earlier than Java 7, you can save the original exception and throw the original exception when an exception occurs in finally:
Java code
Public void read (String filename) throws BaseException {FileInputStream input = null; IOException readException = null; try {input = new FileInputStream (filename);} catch (IOException ex) {readException = ex; // Save the original exception} finally {if (input! = Null) {try {input. close () ;}catch (IOException ex) {if (readException = null) {readException = ex ;}} if (readException! = Null) {throw new BaseException (readException );}}}
In Java 7, you can use the addSuppressed method to record the suppressed exceptions:
Java code
Public void read (String filename) throws IOException {FileInputStream input = null; IOException readException = null; try {input = new FileInputStream (filename);} catch (IOException ex) {readException = ex;} finally {if (input! = Null) {try {input. close ();} catch (IOException ex) {if (readException! = Null) {// difference here readException. addSuppressed (ex) ;}else {readException = ex ;}} if (readException! = Null) {throw readException ;}}}
② Catch clauses can capture multiple exceptions at the same time
Java code
Public void testSequence () {try {Integer. parseInt ("Hello");} catch (NumberFormatException | RuntimeException e) {// use '|' to separate multiple types, one object e }}
③ Try-with-resources statement
Before Java 7, you must disable socket, file, database connection, and other resources in finally;
In java 7, you can apply for resources in the try statement to automatically release the resources (the resource class must implement java. lang. autoCloseable interface. This interface has been implemented for general file and database connections, and the close method will be automatically called ).
Java code
public void read(String filename) throws IOException { try (BufferedReader reader = new BufferedReader(new FileReader(filename))) { StringBuilder builder = new StringBuilder(); String line = null; while((line=reader.readLine())!=null){ builder.append(line); builder.append(String.format("%n")); } return builder.toString(); } }
You can manage multiple resources in the try clause:
Java code
public void copyFile(String fromPath, String toPath) throws IOException { try ( InputStream input = new FileInputStream(fromPath); OutputStream output = new FileOutputStream(toPath) ) { byte[] buffer = new byte[8192]; int len = -1; while( (len=input.read(buffer))!=-1 ) { output.write(buffer, 0, len); } } }
4. Optimization of the Variable Length Parameter Method
Methods for variable length parameters in Java 7 and earlier versions:
Java code
public int sum(int... args) { int result = 0; for (int value : args) { result += value; } return result; }
Collections support
Java code
List
list = new ArrayList
(); list.add("item"); String item = list.get(0); Set
set = new HashSet
(); set.add("item"); Map
map = new HashMap
(); map.put("key", 1); int value = map.get("key");
Now you can:
List
list = ["item"]; String item = list[0]; Set
set = {"item"}; Map
map = {"key" : 1}; int value = map["key"];
2. Automatic Resource Management
Originally:
BufferedReader br = new BufferedReader(new FileReader(path)); try { return br.readLine(); } finally { br.close(); }
Now:
try (BufferedReader br = new BufferedReader(new FileReader(path)) { return br.readLine(); } //You can declare more than one resource to close: try ( InputStream in = new FileInputStream(src); OutputStream out = new FileOutputStream(dest)) { // code }
3. Improved the type reference of the general instance creation (diamond ).
Originally:
Map
> anagrams = new HashMap
>();
Now:
Map
> anagrams = new HashMap<>();
4. The value can be underlined.
int one_million = 1_000_000;
6. binary text
int binary = 0b1001_1001;
Exception catch can be processed at a time, unlike the previous surround layer by layer;
public void newMultiCatch() { try { methodThatThrowsThreeExceptions(); } catch (ExceptionOne | ExceptionTwo | ExceptionThree e) { // log and deal with all Exceptions } }
File read/write will automatically close the stream, instead of explicitly close in finally as before;
public void newTry() { try (FileOutputStream fos = new FileOutputStream("movies.txt"); DataOutputStream dos = new DataOutputStream(fos)) { dos.writeUTF("Java 7 Block Buster"); } catch (IOException e) { // log the exception } }