JDK1.7 features


Published on

Java 1.7 Features

Published in: Technology, News & Politics
1 Comment
  • To download ppt, Pls try this https://chennaitechblog.wordpress.com/2013/05/20/java-7-0-features/
    Are you sure you want to  Yes  No
    Your message goes here
  • Be the first to like this

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

JDK1.7 features

  1. 1. A view of possible small language changesJava 7.0 change summary
  2. 2. CHANGE BULLETIN BOARD Better Integer Literal Improved type inference Enum comparison String switch Chained invocations &Extension methods Improved catch clauses Array notation for Map, List Self type(this) Automatic ResourceManagement New I/O 2 (NIO2)Libraries Fork Join Framework Miscellaneous Things
  3. 3. •What is better Integer Literal ? Before JDK1.7Binary literalsInt mask=0b101010101010; Proposed in JDK1.7With underscores for clarityint mask =0b1010_1010_1010 ;long big =9_234_345_087_780L;
  4. 4. •Improved type inference? Before JDK1.7 ConstructorsMap<String,List<String>> anagrams= new HashMap<String,List<String>>(); Proposed in Jdk1.7 ConstructorsMap<String, List<String>>anagrams = newHashMap<>();
  5. 5. •Improved type inference(cont) Before JDK1.7 Argument Positionspublic <E> Set<E> emptySet() { … }void timeWaitsFor(Set<Man> people){ … }// * Wont compile!timeWaitsFor(Collections.emptySet()); Proposed in Jdk1.7 Argument Positionspublic <E> Set<E> emptySet() { … }void timeWaitsFor(Set<Man> people) {… }// OKtimeWaitsFor(Collections.<Man>emptySet());
  6. 6. •What is new Enum Comparison? Before JDK1.7enum Size { SMALL, MEDIUM, LARGE }if (mySize.compareTo(yourSize) >= 0)System.out.println(“You can wear my pants.”); Proposed in Jdk1.7enum Size { SMALL, MEDIUM,LARGE }if (mySize > yourSize)System.out.println(“You can wear mypants.”);
  7. 7. What is new Switch Case? Before JDK1.7static booleanbooleanFromString(String s){if (s.equals("true")){return true;} else if (s.equals("false")){return false;} else{ throw newIllegalArgumentException(s);}} Proposed in Jdk1.7static booleanbooleanFromString(Strings) {switch(s) {case "true":return true;case "false":return false;default:throw newIllegalArgumentException(s);}}
  8. 8. Chained invocations Before JDK1.7 (chained)class Builder {void setSomething(Something x){ … }void setOther(Other x) { … }Thing result() { … }}Builder builder = new Builder();builder.setSomething(something);builder.setOther(other);Thing thing = builder.result(); Proposed in Jdk1.7class Builder {void setSomething(Something x){ … }void setOther(Other x) { … }Thing result() { … }}Thing thing = new Builder().setSomething(something).setOther(other).result();
  9. 9. Extension Methods Before JDK1.7import java.util.Collections;List<String> list = …;Collections.sort(list); Proposed in Jdk1.7import static java.util.Collections.sort;List<String> list = …;list.sort();
  10. 10. •Improved catch clauses : Catching multiple types Before JDK1.7try{return klass.newInstance();}catch (InstantiationException e){throw new AssertionError(e);}catch (IllegalAccessException e){throw new AssertionError(e);} Proposed in Jdk1.7try {return klass.newInstance();} catch (InstantiationException |IllegalAccessException e) {throw new AssertionError(e);}
  11. 11. •Improved catch clauses : rethrown exceptions Before JDK1.7try {// Throws several typesdoable.doit();}catch (Throwable ex) {logger.log(ex);throw ex; // Error: Throwable notdeclared} Proposed in Jdk1.7try {// Throws several typesdoable.doit();}catch (final Throwable ex) {logger.log(ex);throw ex;// OK: Throws the same several types}
  12. 12. •Array notation for Map, List change Before JDK1.7void swap(List<String>list, int i, int j){String s1 = list.get(i);list.set(i,list.get(j));list.set(j, s1);} Proposed in Jdk1.7void swap(List<String>list, int i, int j){String s1 = list[i];list[i] = list[j];list[j] = s1;}
  13. 13. •Array notation for Map, List change(cont) Before JDK1.7Map<Input,Output> cache = …;Output cachedComputation(Input in) {Output out = cache.get(in);if (out == null) {out = computation(input);cache.put(in, out);}return out;} Proposed in Jdk1.7Map<Input,Output> cache = …;Output cachedComputation(Inputin) {Output out = cache[in];if (out == null) {out = computation(input);cache[in] = out;}return out;}
  14. 14. •What is Self type(this)? Before JDK1.7class Buffer {Buffer flip() { … }Buffer position(int newPos) { … }Buffer limit(int newLimit) { … }}class ByteBuffer extends Buffer {ByteBuffer put(byte data) { … }}public static void main(String args) {ByteBuffer buf = ...;buf.flip().position(12); // OKbuf.flip().put(12); // Error } Proposed in Jdk1.7class Buffer {this flip() { … }this position(int newPos) { … }this limit(int newLimit) { … }}class ByteBuffer extends Buffer {this put(byte data) { … }}public static void main(String args) {ByteBuffer buf = ...;buf.flip().position(12); // OKbuf.flip().put(12); // is fine now}
  15. 15. •Why Automatic Resource Management? Before JDK1.7InputStream in = new FileInputStream(src);try{OutputStream out = new FileOutputStream(dest);try{byte[] buf = new byte[8192];int n;while (n = in.read(buf)) >= 0) out.write(buf, 0, n);} finally {out.close();}} finally {in.close();}
  16. 16. •Why Automatic Resource Management?(cont) Proposed JDK1.7try (InputStream in = new FileInputStream(src),OutputStream out = new FileOutputStream(dest)){byte[] buf = new byte[8192];int n;while (n = in.read(buf)) >= 0)out.write(buf, 0, n);}New superinterface java.lang.AutoCloseable All AutoCloseable and by extension java.io.Closeable types useable with try-with-resources anything with a void close() method is a candidate JDBC 4.1 retrefitted as AutoCloseable too
  17. 17. What is New I/O 2 (NIO2) Libraries? (JSR 203)Original Java I/O APIs presented challenges for developers Not designed to be extensible Many methods do not throw exceptions as expected rename() method works inconsistently Developers want greater access to file metadataJava NIO2 solves these problems
  18. 18. Features of NIO2 (cont) Path is a replacement for File (Biggest impact on developers) Better directory support (list() method can stream via iterator) Entries can be filtered using regular expressions in API Symbolic link support java.nio.file.Filesystem interface to a filesystem (FAT, ZFS, Zip archive, network,etc) java.nio.file.attribute package Access to file metadata
  19. 19. Features of NIO2 (cont)Path Class introduction Equivalent of java.io.File in the new API Immutable Have methods to access and manipulate Path Few ways to create a Path - From Paths and FileSystem//Make a reference to the pathPath home = Paths.get(“/home/fred”);//Resolve tmp from /home/fred -> /home/fred/tmpPath tmpPath = home.resolve(“tmp”);//Create a relative path from tmp -> ..Path relativePath = tmpPath.relativize(home)File file = relativePath.toFile();
  20. 20. Introuction Fork Join FrameworkGoal is to take advantage of multiple processor Designed for task that can be broken down into smallerpiecesEg. Fibonacci number fib(10) = fib(9) + fib(8) Typical algorithm that uses fork joinif I can manage the taskperform the taskelsefork task into x number of smaller/similar taskjoin the results
  21. 21. Introuction Fork Join Framework (cont)Key Classes ForkJoinPoolExecutor service for running ForkJoinTask ForkJoinTaskThe base class for forkjoin task RecursiveActionA subclass of ForkJoinTaskA recursive resultless taskImplements compute() abstract method to performcalculation RecursiveTaskSimilar to RecursiveAction but returns a result
  22. 22. Introuction Fork Join Framework (cont)ForkJoin Example – Fibonaccipublic class Fibonacci extends RecursiveTask<Integer>{private final int number;public Fibonacci(int n) { number = n; }@Override protected Integer compute() {switch (number) {case 0: return (0);case 1: return (1);default:Fibonacci f1 = new Fibonacci(number – 1);Fibonacci f2 = new Fibonacci(number – 2);f1.fork(); f2.fork();return (f1.join() + f2.join());}}}
  23. 23. Introuction Fork Join Framework (cont)ForkJoin Example – FibonacciForkJoinPool pool = new ForkJoinPool();Fibonacci r = new Fibonacci(10);pool.submit(r);while (!r.isDone()) {//Do some work...}System.out.println("Result of fib(10) = "+ r.get());
  24. 24. •Miscellaneous Things InvokeDynamic Bytecode Security Eliptic curve cryptography TLS 1.2 JAXP 1.4.4 JAX-WS 2.2 JAXB 2.2 ClassLoader architecture changes close() for URLClassLoader Javadoc support for CSS