Java 8? Do you remember the Java 7 that year at Daming Lake?

Source: Internet
Author: User
Tags case statement finally block java se

But the new man laughs, which smells the old people cry. When everyone is in the mood to discuss Java 8, that early forgotten Java 7, perhaps you never remember it's good.


The release of Java 8 is also one months old, and I am sure that we are now exploring the new features in JDK 8. But before you start delving into Java 8, it's a good idea to review what new features are in Java 7. If you remember, Java 6 doesn't add any features, it's just a few changes to the JVM and a performance boost, but JDK 7 adds a lot of power to help improve development efficiency. What is the purpose of my writing this article now? Why do I still talk about Java1.7 when everyone else is talking about Java 8? Because I don't think all Java developers are aware of the changes in JDK 7, and when is it more appropriate to introduce the features of the previous version than when the new version is released? I also rarely see developers using automatic resource management (ARM) in their code, although the IDE's assistive tools already support this feature. However, it is true to see someone using the switch function of string and <> doing type deduction, and few people know the fork-join framework, or catch multiple exceptions in a catch block, or use underscores in numeric literals. So I take this opportunity to write a brief summary of the changes that will facilitate our daily development efforts. NiO and the new file interface, along with many API-level changes, are also noteworthy. I believe that when combined with the lambda expression of Java 8, the code written will definitely be more concise.


Type deduction

JDK 1.7 introduces a new operator, <>, also known as the diamond operator, which allows the construction method to be type-deduced as well. Prior to Java 7, type inference was only available for methods, as Joshua Bloch in the second edition of Effiective Java, which is now finally implemented in the constructor method. Before that, you have to specify the type at the left and right sides of the object creation expression, and now you just need to specify it on the left, just like this.


Before JDK 7

map<string, list<string>> employeerecords = new hashmap<string, list<string>> (); List<integer> primes = new arraylist<integer> ();

JDK 7

map<string, list<string>> employeerecords = new hashmap<> (); List<integer> primes = new arraylist<> ();

In Java 7, you can use less code, especially when using collections, where generics are used extensively. Click here to learn more about the Java diamond operator. (the original does not provide a link AH)


Support for string in switch

Before JDK 7, only integer types can be used as a selection factor for the Switch-case statement. In JDK7, you can use a string as the selection factor. Like what:

String state = "NEW";   Switch (day) {case ' new ': System.out.println ("Order is in NEW State"); 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"); }

The Equals and Hashcode () methods of string are used when comparing, so this comparison is case-sensitive. The advantage of using string in switch is that the compiler can generate more efficient code than directly using If-else. For more detailed instructions please click here.


Automated resource Management (Automatic Resource Management)

Before JDK 7, we needed to use a finally block to ensure that the resources were actually freed, whether the try block was completed or interrupted. For example, when reading files or input streams, we need to close them in the finally block, which leads to a lot of boilerplate code, like this:

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 ();09                 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, is not a lot of boilerplate code?


In Java 7, you can use the Try-with-resource features to automatically shut down resources, as long as the implementation of the Autoclosable and cloaeable interface can be, Stream, File, Socket, database connection has been implemented. JDK 7 introduces the Try-with-resource statement to make sure that each resource calls the close () method of the Autoclosable interface to shut down after the statement ends. Here's a sample code from Java 7 that looks much more concise:

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.ou T.println ("Can ' t read the file"); }}

Since Java is responsible for shutting down those open resources such as files and streams, the disclosure of file descriptors should no longer occur, and there should be no more hints for file descriptor errors. Even the JDBC 4.1 has started to support the autoclosable.


Fork Join Frame

The Fork/join framework is the implementation of the Executorservice interface, which allows you to take advantage of the benefits of modern server multiprocessor. This framework is designed for work that can be recursively split into smaller tasks. Its goal is to squeeze the processor's ability to improve the performance of the program. As with other Executorservice implementations, the Fork/join framework also distributes tasks to multiple threads in the thread pool. The difference is that it uses a work-stealing algorithm (work-stealing algorithm), which differs greatly from the algorithm of the producer consumer. A worker thread that has finished working on a task can steal some tasks from other busy threads to execute. The core of the Fork/join framework is the Forkjoinpool class, which inherits from Abstractexecutorservice. The Forkjoinpool class implements the core work-stealing algorithm that can perform the forkjointask process. You can encapsulate the code in a Forkjointask subclass, such as Recursivetask or recursiveaction. For more information, see here.


Use underscores in numeric literals

In JDK 7, you can use ' _ ' in numeric literals to improve readability. This is especially useful for people who use large numbers in the source code, for example in the financial or computational field. Say So,

int billion = 1_000_000_000; 10^9long creditcardnumber = 1234_4567_8901_2345l; Digit Numberlong SSN = 777_99_8888l;double PI = 3.1415_9265;float pif = 3.14_15_92_65f;

You can insert an underscore in the right place to make it more readable, for example, a large number can be underlined every three digits, for credit card numbers, usually 16 bits, and you can underline every 4 numbers as they appear on the card. " By the way, remember that you can't drop the line after the decimal, or where the number starts and ends. For example, the following numeric literals are incorrect because they use underscores incorrectly:

Double pi = 3._1415_9265; Underscore just after decimal pointlong creditcardnum = 1234_4567_8901_2345_l; Underscore at the end of numberlong ssn = _777_99_8888l; Undersocre at the beginning

You can read my article to learn more about the underline use examples.


Capturing multiple exceptions in a catch block

In JDK 7, a single catch block can handle multiple exception types.


For example, before JDK 7, if you want to capture two types of exceptions, you need two catch blocks, although the two processing logic is the same:

try {...} catch (ClassNotFoundException ex) {ex.printstacktrace ();} catch (SQLException ex) {Ex.printstacktrac E ();}

In JDK 7, you only have to use a catch block to get it done, the exception type with ' | ' To separate:

try {...} catch (classnotfoundexception| SQLException ex) {ex.printstacktrace ();}

By the way, this usage does not include the subtype of the exception. For example, the following multiple exception capture statement throws a compilation error:

try {...} catch (FileNotFoundException | IOException ex) {ex.printstacktrace ();}

This is because FileNotFoundException is a subclass of IOException and throws the following error at compile time: Java.io.FileNotFoundException is a subclass of alternative Java.io.IOException at Test.main (test.java:18).


For more information, please click here.


Binary literals using the "OB" prefix

In JDK7, for integer types (byte, short, int, and long), you can use the ' 0b ' prefix to indicate that this is a binary literal, just like in C + +. Before that, you can only use 8 binary (prefix ' 0 ') or 16 (prefix ' 0x ' or ' 0X ') literal.

int mask = 0b01010000101;

The benefits of this writing are more pronounced:

int binary = 0b0101_0000_1010_0010_1101_0000_1010_0010;

8.Java NIO 2


The Java.nio.file package, along with the associated Java.nio.file.attibute package, has been introduced in Java SE 7 to fully support file IO and access to the default file system. It also introduces the path class, which you can use to represent any path in the operating system. The new file system API is compatible with the old version and provides several very useful methods that can be used to check, delete, copy and move files. For example, you can determine whether a file is a hidden file in Java. You can also create soft links and hard links in Java. The new file API for JDK 7 also enables you to search for files using wildcards. You can also use it to monitor whether a directory is changed. I recommend that you look at its official documentation to learn more about some interesting features.


G1 garbage collector

JDK7 introduces a new garbage collector, G1, which is the abbreviation for garbage first. The G1 collector takes precedence over the area of garbage collection. In order to implement this strategy it divides the heap into multiple areas, just like Java 7 was divided into three regions (Cenozoic, Laosheng, and persistent generations). The G1 collector is a predictable collector, and it also guarantees high throughput for memory-intensive programs.


Improvement of the re-throwing anomaly

The compiler for Java SE 7 has a more accurate analysis of the re-throwing exception than the previous version. This allows you to specify a more precise exception type in the throws clause of the method declaration. Prior to JDK 7, the type of the re-thrown exception was considered to be the specified exception type in the Catch parameter. For example, if you throw a parseexception and a ioexception in your try block, in order to catch all the exceptions and then re-throw them, you will catch the exception type of exception, and declare that the exception type that your method throws is exception. This is a bit less precise, because what you actually throw is a generic exception type, and the statement that calls your method needs to catch the generic exception. Take a look at this exception-handling code before Java 1.7. You might be more aware of this:

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; }}

After JDK 7, you can specify the exception type explicitly in the throws clause of the method. Accurate exception re-throw refers to the fact that if you re-throw an exception in a catch block, the actual type of exception actually thrown is:


The exception that your try block throws

has not been processed by the previous catch block, and

The parameter type of a catch is a subclass of exception.

This makes the exception re-cast more precise. You can know more exactly what kind of exception the method throws, so you can handle them better, like this code:

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 compiler for Java SE 7 allows you to specify parseexception and IOException types in the throws clause of the Preciese () method declaration, because the exception you throw is the parent class of these exception types declared. For example, here we throw the java.lang.Exception, which is the parent class for all the checked exceptions. In some places you will see the final keyword in the catch parameter, but this is no longer mandatory.


These are all the things you should review in JDK 7. These new features are useful for writing clean code and improving development efficiency. With the lambda expression in Java 8, the code in Java has a new milestone in its neat way. If you think I missed out on any of the useful features of Java 1.7 in this article, please remember to remind me.


P.S. If you like reading, then you will also like packet publication of this Java 7 New features Cookbook.



Java 8? Do you remember the Java 7 that year at Daming Lake?

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.