10 Jdk Seven Features To Revisit, Earlier You Lot Welcome Coffee 8

It's been almost a calendar month Java 8 is released too I am certain all of yous are exploring novel features of JDK 8. But, before yous completely delve into Java 8, it’s fourth dimension to revisit about of the cool features introduced on Java 7. If yous remember, Java half dozen was zilch on feature, it was all well-nigh JVM changes too performance, but JDK vii did introduced about cool features which improved developer's solar daytime to solar daytime task. Why I am writing this ship service now? Why I am talking well-nigh Java 1. 7, when everybody is talking well-nigh Java 8? Well I think, non all Java developers are familiar amongst changes introduced inwards JDK 7, too what fourth dimension tin live amend to revisit before version than before welcoming a novel version.

I don't encounter automatic resources management used past times developer inwards daily life, fifty-fifty later on IDE's has got content assist for that. Though I encounter programmers using String inwards Switch too Diamond operator for type inference, 1 time again in that location is real footling known well-nigh fork bring together framework,  catching multiple exception inwards 1 grab block or using underscore on numeric literals.

So I took this chance to write a summary form of ship service to revise these convenient changes too adopt them into out daily programming life. There are duet of adept changes on NIO too novel File API, too lots of other at API level, which is also worth looking. I am certain combined amongst Java 8 lambda expression, these characteristic volition outcome inwards much amend too cleaner code.


1) Type inference

Before JDK 1.7 innovate a novel operator <<, known equally diamond operator to making type inference available for constructors equally well. Prior to Java 7, type inference is entirely available for methods, too Joshua Bloch has rightly predicted inwards Effective Java 2d Edition, it’s right away available for constructor as well.


Prior JDK 7, yous type to a greater extent than to specify types on both left too correct manus side of object creation expression, but right away it entirely needed on left manus side, equally shown inwards below example.

Prior JDK 7
Map<String, List<String>> employeeRecords =  new HashMap<String, List<String>>(); List<Integer> primes = new ArrayList<Integer>();

In JDK 7
Map<String, List<String>> employeeRecords =  new HashMap<>(); List<Integer> primes = new ArrayList<>();

So yous remove maintain to type less inwards Java 7, spell working amongst Collections, where nosotros heavily work Generics. See hither for to a greater extent than detailed information on diamond operator inwards Java.


2) String inwards Switch

Before JDK 7, entirely integral types tin live used equally selector for switch-case statement. In JDK 7, yous tin work a String object equally the selector. For example,
String terra firma = "NEW";  switch (day) {    case "NEW": System.out.println("Order is inwards 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() too hashcode() method from java.lang.String is used inwards comparison, which is case-sensitive. Benefit of using String inwards switch is that, Java compiler tin generate to a greater extent than efficient code than using nested if-then-else statement. See hither for to a greater extent than detailed information of how to work String on Switch instance statement.


3) Automatic Resource Management

Before JDK 7, nosotros demand to work a finally block, to ensure that a resources is closed regardless of whether the endeavour contention completes usually or abruptly, for illustration spell reading files too streams, nosotros demand to unopen them into lastly block, which outcome inwards lots of boiler plate too messy code, equally 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 non 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 unopen files");             }         }     }

Look at this code, how many lines of boiler codes?

Now inwards Java 7, yous tin work try-with-resource characteristic to automatically unopen resources, which implements AutoClosable and Closeable interface e.g. Streams, Files, Socket handles, database connections etc. JDK vii introduces a try-with-resources statement, which ensures that each of the resources inwards try(resources) is closed at the destination of the contention past times calling close() method of AutoClosable. Now same illustration inwards Java vii volition hold back similar below, a much concise too 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 non found");  } catch (IOException ex) {   System.out.println("Can't read the file");  } }
Since Java is taking aid of closing opened resources including files too streams, may live no to a greater extent than leaking of file descriptors too likely an destination to file descriptor error. Even JDBC 4.1 is retrofitted equally AutoClosable too.

4) Fork Join Framework

The fork/join framework is an implementation of the ExecutorService interface that allows yous to remove maintain wages of multiple processors available inwards modern servers. It is designed for piece of work that tin live broken into smaller pieces recursively. The goal is to work all the available processing might to heighten the functioning of your application. As amongst whatever ExecutorService implementation, the fork/join framework distributes tasks to worker threads inwards a thread pool. The fork bring together framework is distinct because it uses a work-stealing algorithm, which is real dissimilar than producer consumer algorithm. Worker threads that run out of things to make tin steal tasks from other threads that are even therefore busy. The pump of the fork/join framework is the ForkJoinPool class, an extension of the AbstractExecutorService class. ForkJoinPool implements the centre work-stealing algorithm too tin execute ForkJoinTask processes. You tin roll code inwards a ForkJoinTask subclass similar RecursiveTask (which tin render a result) or RecursiveAction. See here for about to a greater extent than information on fork bring together framework inwards Java.


5) Underscore inwards Numeric literals

In JDK 7, yous could insert underscore(s) '_' inwards betwixt the digits inwards an numeric literals (integral too floating-point literals) to improve readability. This is peculiarly valuable for people who uses large numbers inwards source files, may live useful inwards finance too 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;
 
You tin seat underscore at convenient points to acquire inwards to a greater extent than readable, for examples for large amounts putting underscore betwixt 3 digits brand sense, too for credit carte du jour numbers, which are xvi digit long, putting underscore later on quaternary digit brand sense, equally they are printed inwards cards. By the means shout out upward that yous cannot seat underscore, but later on decimal reveal or at the get-go or at the destination of number. For example, next numeric literals are invalid, because of incorrect placement of underscore:

double pi = 3._1415_9265; // underscore but later on decimal point long creditcardNum = 1234_4567_8901_2345_L; //underscore at the destination of number long ssn = _777_99_8888L; //undersocre at the beginning

See my ship service well-nigh how to work underscore on numeric literals for to a greater extent than information too work case.

6) Catching Multiple Exception Type inwards Single Catch Block

 is released too I am certain all of yous are exploring novel features of JDK  10 JDK vii Features to Revisit, Before You Welcome Java 8In JDK 7, a unmarried grab block tin remove maintain to a greater extent than than 1 exception types.

For example, before JDK 7, yous demand 2 grab blocks to grab 2 exception types although both perform identical task:

try {     ......  } catch(ClassNotFoundException ex) {    ex.printStackTrace(); } catch(SQLException ex) {    ex.printStackTrace(); }

In JDK 7, yous could work 1 unmarried grab block, amongst exception types separated past times '|'.

try {     ......  } catch(ClassNotFoundException|SQLException ex) {     ex.printStackTrace();  }

By the way, but shout out upward that Alternatives inwards a multi-catch contention cannot live related past times sub classing. For illustration a multi-catch contention similar below volition throw compile fourth dimension mistake :

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

Alternatives inwards a multi-catch contention cannot live related past times sub classing, it volition throw mistake at compile fourth dimension :
java.io.FileNotFoundException is a subclass of choice java.io.IOException
        at Test.main(Test.java:18)

encounter hither to larn to a greater extent than well-nigh improved exception treatment inwards Java SE 7.


7) Binary Literals amongst prefix "0b"

In JDK 7, yous tin limited literal values inwards binary amongst prefix '0b' (or '0B') for integral types (byte, short, int and long), similar to C/C++ language. Before JDK 7, yous tin entirely work octal values (with prefix '0') or hexadecimal values (with prefix '0x' or '0X').

int mask = 0b01010000101;

or fifty-fifty better

int binary = 0B0101_0000_1010_0010_1101_0000_1010_0010;


8) Java NIO 2.0

Java SE vii introduced java.nio.file packet too its related package, java.nio.file.attribute, supply comprehensive back upward for file I/O too for accessing the default file system. It also introduced the Path class which allow yous to stand upward for whatever path inwards operating system. New File organization API complements older 1 too provides several useful method checking, deleting, copying, too moving files. for example, right away yous tin check if a file is hidden inwards Java. You tin also create symbolic too difficult links from Java code.  JDK vii novel file API is also capable of searching for files using wild cards. You also acquire back upward to sentinel a directory for changes. I would recommend to banking company check Java medico of novel file packet to larn to a greater extent than well-nigh this interesting useful feature.


9) G1 Garbage Collector

JDK vii introduced a novel Garbage Collector known equally G1 Garbage Collection, which is brusk cast of garbage first. G1 garbage collector performs clean-up where in that location is most garbage. To attain this it carve upward Java heap memory into multiple regions equally opposed to 3 regions inwards the prior to Java vii version (new, erstwhile too permgen space). It's said that G1 is quite predictable too provides greater through seat for retentivity intensive applications.


10) More Precise Rethrowing of Exception

The Java SE vii compiler performs to a greater extent than precise analysis of re-thrown exceptions than before releases of Java SE. This enables yous to specify to a greater extent than specific exception types inwards the throws clause of a method declaration. before JDK 7, re-throwing an exception was treated equally throwing the type of the grab parameter. For example, if your endeavour block tin throw ParseException as good equally IOException. In gild to grab all exceptions too rethrow them, yous would remove maintain to grab Exception too declare your method equally throwing an Exception. This is form of obscure non-precise throw, because yous are throwing a full general Exception type (instead of specific ones) too statements calling your method demand to grab this full general Exception. This volition live to a greater extent than clear past times seeing next illustration of exception treatment inwards code prior to Java 1.7

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

From JDK vii onwards yous tin live to a greater extent than precise spell declaring type of Exception inwards throws clause of whatever method. This precision inwards determining which Exception is thrown from the fact that, If yous re-throw an exception from a grab block, yous are genuinely throwing an exception type which:

   1) your endeavour block tin throw,
   2) has non handled past times whatever previous grab block, and
   3) is a subtype of 1 of the Exception declared equally grab parameter

This leads to improved checking for re-thrown exceptions. You tin live to a greater extent than precise well-nigh the exceptions beingness thrown from the method too yous tin remove maintain them a lot amend at customer side, equally shown inwards next illustration :

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 vii compiler allows yous to specify the exception types ParseException and IOException in the throws clause inwards the preciese() method annunciation because yous tin re-throw an exception that is a super-type of whatever of the types declared inwards the throws, nosotros are throwing java.lang.Exception, which is super degree of all checked Exception. Also inwards about places yous volition encounter concluding keyword amongst grab parameter, but that is non mandatory whatever more.

That's all well-nigh what yous tin revise inwards JDK 7. All these novel features of Java vii are real helpful inwards your goal towards create clean code too developer productivity. With lambda aspect introduced inwards Java 8, this goal to cleaner code inwards Java has reached about other milestone. Let me know, if yous intend I remove maintain left out whatever useful characteristic of Java 1.7, which yous intend should live here.


Further Learning
The Complete Java MasterClass
tutorial)
  • How to work Stream degree inwards Java 8 (tutorial)
  • How to work filter() method inwards Java 8 (tutorial)
  • How to work forEach() method inwards Java 8 (example)
  • How to bring together String inwards Java 8 (example)
  • How to convert List to Map inwards Java 8 (solution)
  • How to work peek() method inwards Java 8 (example)
  • 5 Books to Learn Java 8 from Scratch (books)
  • How to convert current to array inwards Java 8 (tutorial)
  • Java 8 Certification FAQ (guide)
  • Java 8 Mock Exams too Practice Test (test)

  • Thanks for reading this article therefore far. If yous similar this article too therefore delight part amongst your friends too colleagues. If yous remove maintain whatever question, doubt, or feedback too therefore delight drib a comment too I'll endeavour to answer your question.

    P.S. : If yous desire to larn to a greater extent than well-nigh novel features inwards Java 8 too therefore delight encounter the tutorial What's New inwards Java 8. It explains well-nigh all of import features of Java 8 e.g. lambda expressions, streams, functional inteface, Optionals, novel appointment too fourth dimension API too other miscelleneous changes.

    P.S. : If yous honey books too therefore yous may similar Java vii New features Cookbook from Packet Publication equally well. 

    Komentar

    Postingan populer dari blog ini

    Difference Betwixt Struts Validatorform Vs Validatoractionform - Interview Question

    How To Convert Inputstream To Byte Array Inwards Coffee - Two Examples

    Difference Betwixt Fileinputstream Together With Filereader Inwards Coffee | Inputstream Vs Reader