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

10 Jdk Seven Features To Revisit, Earlier You Lot Welcome Coffee 8 - Hallo sahabat BEST LEARNING JAVA, Pada Artikel yang anda baca kali ini dengan judul 10 Jdk Seven Features To Revisit, Earlier You Lot Welcome Coffee 8, kami telah mempersiapkan artikel ini dengan baik untuk anda baca dan ambil informasi didalamnya. mudah-mudahan isi postingan Artikel core java, Artikel Java 7, Artikel Java 8, yang kami tulis ini dapat anda pahami. baiklah, selamat membaca.

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

Baca juga


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

It's been almost a calendar month Java 8 is released in addition to 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 around of the cool features introduced on Java 7. If yous remember, Java six was nada on feature, it was all nearly JVM changes in addition to performance, but JDK vii did introduced around cool features which improved developer's solar daytime to solar daytime task. Why I am writing this post now? Why I am talking nearly Java 1. 7, when everybody is talking nearly Java 8? Well I think, non all Java developers are familiar amongst changes introduced inward JDK 7, in addition to what fourth dimension tin live on ameliorate to revisit before version than before welcoming a novel version.

I don't run across automatic resources management used yesteryear developer inward daily life, fifty-fifty afterwards IDE's has got content assist for that. Though I run across programmers using String inward Switch in addition to Diamond operator for type inference, i time to a greater extent than at that topographic point is really niggling known nearly fork bring together framework,  catching multiple exception inward i select take away maintain of block or using underscore on numeric literals.

So I took this chance to write a summary form of post to revise these convenient changes in addition to adopt them into out daily programming life. There are span of expert changes on NIO in addition to novel File API, in addition to lots of other at API level, which is also worth looking. I am certain combined amongst Java 8 lambda expression, these characteristic volition trial inward much ameliorate in addition to cleaner code.


1) Type inference

Before JDK 1.7 innovate a novel operator <<, known every bit diamond operator to making type inference available for constructors every bit well. Prior to Java 7, type inference is alone available for methods, in addition to Joshua Bloch has rightly predicted inward Effective Java sec Edition, it’s straightaway available for constructor as well.


Prior JDK 7, yous type to a greater extent than to specify types on both left in addition to correct manus side of object creation expression, but straightaway it alone needed on left manus side, every bit shown inward 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 receive got to type less inward Java 7, piece working amongst Collections, where nosotros heavily utilisation Generics. See hither for to a greater extent than detailed information on diamond operator inward Java.


2) String inward Switch

Before JDK 7, alone integral types tin live on used every bit selector for switch-case statement. In JDK 7, yous tin utilisation a String object every bit the selector. For example,
String solid soil = "NEW";  switch (day) {    case "NEW": System.out.println("Order is inward 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() in addition to hashcode() method from java.lang.String is used inward comparison, which is case-sensitive. Benefit of using String inward 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 utilisation String on Switch instance statement.


3) Automatic Resource Management

Before JDK 7, nosotros demand to utilisation a finally block, to ensure that a resources is closed regardless of whether the endeavor contention completes usually or abruptly, for illustration piece reading files in addition to streams, nosotros demand to closed them into finally block, which trial inward lots of boiler plate in addition to messy code, every bit 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 closed files");             }         }     }

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

Now inward Java 7, yous tin utilisation try-with-resource characteristic to automatically closed 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 inward try(resources) is closed at the halt of the contention yesteryear calling close() method of AutoClosable. Now same illustration inward Java vii volition expect similar below, a much concise in addition to 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 tending of closing opened resources including files in addition to streams, may live on no to a greater extent than leaking of file descriptors in addition to likely an halt to file descriptor error. Even JDBC 4.1 is retrofitted every bit AutoClosable too.

4) Fork Join Framework

The fork/join framework is an implementation of the ExecutorService interface that allows yous to accept payoff of multiple processors available inward modern servers. It is designed for piece of job that tin live on broken into smaller pieces recursively. The destination is to utilisation all the available processing mightiness to get upward the functioning of your application. As amongst whatsoever ExecutorService implementation, the fork/join framework distributes tasks to worker threads inward a thread pool. The fork bring together framework is distinct because it uses a work-stealing algorithm, which is really dissimilar than producer consumer algorithm. Worker threads that run out of things to make tin steal tasks from other threads that are notwithstanding busy. The oculus of the fork/join framework is the ForkJoinPool class, an extension of the AbstractExecutorService class. ForkJoinPool implements the center work-stealing algorithm in addition to tin execute ForkJoinTask processes. You tin roll code inward a ForkJoinTask subclass similar RecursiveTask (which tin render a result) or RecursiveAction. See here for around to a greater extent than information on fork bring together framework inward Java.


5) Underscore inward Numeric literals

In JDK 7, yous could insert underscore(s) '_' inward betwixt the digits inward an numeric literals (integral in addition to floating-point literals) to improve readability. This is specially valuable for people who uses large numbers inward source files, may live on useful inward finance in addition to 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 become far to a greater extent than readable, for examples for large amounts putting underscore betwixt 3 digits brand sense, in addition to for credit menu numbers, which are sixteen digit long, putting underscore afterwards fourth digit brand sense, every bit they are printed inward cards. By the agency retrieve that yous cannot seat underscore, simply afterwards decimal divulge or at the get-go or at the halt of number. For example, next numeric literals are invalid, because of incorrect placement of underscore:

double pi = 3._1415_9265; // underscore simply afterwards decimal point long creditcardNum = 1234_4567_8901_2345_L; //underscore at the halt of number long ssn = _777_99_8888L; //undersocre at the beginning

See my post nearly how to utilisation underscore on numeric literals for to a greater extent than information in addition to utilisation case.

6) Catching Multiple Exception Type inward Single Catch Block

 is released in addition to 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 select take away maintain of block tin grip to a greater extent than than i exception types.

For example, before JDK 7, yous demand 2 select take away maintain of blocks to select take away maintain of 2 exception types although both perform identical task:

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

In JDK 7, yous could utilisation i unmarried select take away maintain of block, amongst exception types separated yesteryear '|'.

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

By the way, simply retrieve that Alternatives inward a multi-catch contention cannot live on related yesteryear sub classing. For illustration a multi-catch contention similar below volition throw compile fourth dimension fault :

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

Alternatives inward a multi-catch contention cannot live on related yesteryear sub classing, it volition throw fault at compile fourth dimension :
java.io.FileNotFoundException is a subclass of option java.io.IOException
        at Test.main(Test.java:18)

run across hither to larn to a greater extent than nearly improved exception treatment inward Java SE 7.


7) Binary Literals amongst prefix "0b"

In JDK 7, yous tin limited literal values inward binary amongst prefix '0b' (or '0B') for integral types (byte, short, int and long), similar to C/C++ language. Before JDK 7, yous tin alone utilisation 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 parcel in addition to its related package, java.nio.file.attribute, render comprehensive back upward for file I/O in addition to for accessing the default file system. It also introduced the Path class which allow yous to stand upward for whatsoever path inward operating system. New File organisation API complements older i in addition to provides several useful method checking, deleting, copying, in addition to moving files. for example, straightaway yous tin check if a file is hidden inward Java. You tin also create symbolic in addition to 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 scout a directory for changes. I would recommend to cheque Java medico of novel file parcel to larn to a greater extent than nearly this interesting useful feature.


9) G1 Garbage Collector

JDK vii introduced a novel Garbage Collector known every bit G1 Garbage Collection, which is brusk cast of garbage first. G1 garbage collector performs clean-up where at that topographic point is most garbage. To attain this it dissever Java heap memory into multiple regions every bit opposed to 3 regions inward the prior to Java vii version (new, quondam in addition to permgen space). It's said that G1 is quite predictable in addition to provides greater through seat for retentiveness 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 inward the throws clause of a method declaration. before JDK 7, re-throwing an exception was treated every bit throwing the type of the select take away maintain of parameter. For example, if your endeavor block tin throw ParseException as good every bit IOException. In fellowship to select take away maintain of all exceptions in addition to rethrow them, yous would receive got to select take away maintain of Exception in addition to declare your method every bit throwing an Exception. This is form of obscure non-precise throw, because yous are throwing a full general Exception type (instead of specific ones) in addition to statements calling your method demand to select take away maintain of this full general Exception. This volition live on to a greater extent than clear yesteryear seeing next illustration of exception treatment inward 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 on to a greater extent than precise piece declaring type of Exception inward throws clause of whatsoever method. This precision inward determining which Exception is thrown from the fact that, If yous re-throw an exception from a select take away maintain of block, yous are genuinely throwing an exception type which:

   1) your endeavor block tin throw,
   2) has non handled yesteryear whatsoever previous select take away maintain of block, and
   3) is a subtype of i of the Exception declared every bit select take away maintain of parameter

This leads to improved checking for re-thrown exceptions. You tin live on to a greater extent than precise nearly the exceptions existence thrown from the method in addition to yous tin grip them a lot ameliorate at customer side, every bit shown inward 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 inward the preciese() method annunciation because yous tin re-throw an exception that is a super-type of whatsoever of the types declared inward the throws, nosotros are throwing java.lang.Exception, which is super cast of all checked Exception. Also inward around places yous volition run across in conclusion keyword amongst select take away maintain of parameter, but that is non mandatory whatsoever more.

That's all nearly what yous tin revise inward JDK 7. All these novel features of Java vii are really helpful inward your destination towards create clean code in addition to developer productivity. With lambda facial expression introduced inward Java 8, this destination to cleaner code inward Java has reached around other milestone. Let me know, if yous intend I receive got left out whatsoever useful characteristic of Java 1.7, which yous intend should live on here.


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

  • Thanks for reading this article hence far. If yous similar this article hence delight portion amongst your friends in addition to colleagues. If yous receive got whatsoever question, doubt, or feedback hence delight drib a comment in addition to I'll endeavor to response your question.

    P.S. : If yous desire to larn to a greater extent than nearly novel features inward Java 8 hence delight run across the tutorial What's New inward Java 8. It explains nearly all of import features of Java 8 e.g. lambda expressions, streams, functional inteface, Optionals, novel appointment in addition to fourth dimension API in addition to other miscelleneous changes.

    P.S. : If yous dearest books hence yous may similar Java vii New features Cookbook from Packet Publication every bit well. 


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

    Sekianlah artikel 10 Jdk Seven Features To Revisit, Earlier You Lot Welcome Coffee 8 kali ini, mudah-mudahan bisa memberi manfaat untuk anda semua. baiklah, sampai jumpa di postingan artikel lainnya.

    Anda sekarang membaca artikel 10 Jdk Seven Features To Revisit, Earlier You Lot Welcome Coffee 8 dengan alamat link https://bestlearningjava.blogspot.com/2019/04/10-jdk-seven-features-to-revisit.html

    Belum ada Komentar untuk "10 Jdk Seven Features To Revisit, Earlier You Lot Welcome Coffee 8"

    Posting Komentar

    Iklan Atas Artikel

    Iklan Tengah Artikel 1

    Iklan Tengah Artikel 2

    Iklan Bawah Artikel