Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.
Oliver Doepner    - Java Lunch & Learn 2012 -        Upgrading to Java 7                       http://doepner.net/        ...
Oliver Doepner   - Java Lunch & Learn 2012 -Agenda 1) Why upgrade? 2) Java 7 code examples 3) Corrected behaviours
Oliver Doepner   - Java Lunch & Learn 2012 -Why upgrade?Maturity • 1 year since GA • 9 updates with security   and bug fix...
Oliver Doepner   - Java Lunch & Learn 2012 -Why upgrade?Supported platforms • Windows x86, x64 • Linux x86, x64 • MacOS X ...
Oliver Doepner    - Java Lunch & Learn 2012 -Why upgrade?Some feature highlights • Language features (“Project Coin”) • JV...
Oliver Doepner      - Java Lunch & Learn 2012 -Java 7 code examplesMiscellaneous language changes •   Binary literals, und...
Oliver Doepner   - Java Lunch & Learn 2012 -Binary literals, underscores in numeric literals   long creditCardNumber = 123...
Oliver Doepner     - Java Lunch & Learn 2012 -Strings in switch statementString getSeason(String month) {       switch (mo...
Oliver Doepner      - Java Lunch & Learn 2012 -Generic type inference (“diamond”)Java 5 and 6:   Map<String, List<String>>...
Oliver Doepner       - Java Lunch & Learn 2012 -Simplified varargs method invocationIn Java 6 and older:    List<List<Inte...
Oliver Doepner      - Java Lunch & Learn 2012 -Multi-catchvoid something() throws IOException, SQLException {};Java 6:    ...
Oliver Doepner         - Java Lunch & Learn 2012 -Try-with-resourcesJava 6:String firstLine(String path) throws IOExceptio...
Oliver Doepner     - Java Lunch & Learn 2012 -More precise re-throwHow would you do something like this in Java 6 ?JarFile...
Oliver Doepner         - Java Lunch & Learn 2012 -Revised File I/O (“NIO.2”)Built around the java.nio.Path and java.nio.Fi...
Oliver Doepner         - Java Lunch & Learn 2012 -Corrected behaviourInteresting caveats fromhttp://www.oracle.com/technet...
Upcoming SlideShare
Loading in …5
×

Upgrading to Java 7

865 views

Published on

Shows new Java 7 language features with code examples and gives some motivation for upgrading

Published in: Technology
  • Be the first to comment

Upgrading to Java 7

  1. 1. Oliver Doepner - Java Lunch & Learn 2012 - Upgrading to Java 7 http://doepner.net/ Presentation by Oliver Doepner Halifax 2012
  2. 2. Oliver Doepner - Java Lunch & Learn 2012 -Agenda 1) Why upgrade? 2) Java 7 code examples 3) Corrected behaviours
  3. 3. Oliver Doepner - Java Lunch & Learn 2012 -Why upgrade?Maturity • 1 year since GA • 9 updates with security and bug fixes • Supported by all major IDEs, app servers • JRE 7 is default download • JRE auto-update to come soonJava 6 EOL: Last public updates in Feb 2013
  4. 4. Oliver Doepner - Java Lunch & Learn 2012 -Why upgrade?Supported platforms • Windows x86, x64 • Linux x86, x64 • MacOS X x64 • Solaris x86, x64, Sparc • Linux ARM v6, v7
  5. 5. Oliver Doepner - Java Lunch & Learn 2012 -Why upgrade?Some feature highlights • Language features (“Project Coin”) • JVM supports invokedynamic • JVM performance improvements • Much better file handling API (“NIO.2“) • fork/join frameworkMore: http://docs.oracle.com/javase/7/docs/webnotes/adoptionGuide/
  6. 6. Oliver Doepner - Java Lunch & Learn 2012 -Java 7 code examplesMiscellaneous language changes • Binary literals, underscores in numeric literals • Strings in switch statement • Generic type inference (“diamond”) • Simplified varargs method invocationException handling New or revised APIs • Try-with-resources • Fork / join • Multi-catch • New File I/O (“NIO.2”) • More precise re-throw
  7. 7. Oliver Doepner - Java Lunch & Learn 2012 -Binary literals, underscores in numeric literals long creditCardNumber = 1234_5678_9012_3456L; long socialSecurityNumber = 999_99_9999L; float pi = 3.14_15F; long hexBytes = 0xFF_EC_DE_5E; long hexWords = 0xCAFE_BABE; long maxLong = 0x7fff_ffff_ffff_ffffL; byte nybbles = 0b0010_0101; long bytes = 0b11010010_01101001_10010100_10010010; • 0b prefix for binary literals • Any number of underscore characters can appear anywhere between digits.
  8. 8. Oliver Doepner - Java Lunch & Learn 2012 -Strings in switch statementString getSeason(String month) { switch (month) { case "Jan": case "Feb": return "Winter"; case "Mar": case "Apr": case "May": return "Spring"; case "Jan": case "Jul": case "Aug": return "Summer"; case "oct": case "Nov": return "Fall"; default: throw new IllegalArgumentException("Invalid month"); } }
  9. 9. Oliver Doepner - Java Lunch & Learn 2012 -Generic type inference (“diamond”)Java 5 and 6: Map<String, List<String>> myMap = new HashMap<String, List<String>>();Java 7: Map<String, List<String>> myMap = new HashMap<>();Use <>, not raw type: Map<String, List<String>> myMap = new HashMap();This both works: List<String> list1 = new ArrayList<>(); List<? extends String> list2 = new ArrayList<>();But this does not work: void myMethod(List<String> l) { } myMethod(new ArrayList<>());=> Compilation error: ”The method myMethod(List<String>) ... is notapplicable for the arguments (ArrayList<Object>)”
  10. 10. Oliver Doepner - Java Lunch & Learn 2012 -Simplified varargs method invocationIn Java 6 and older: List<List<Integer>> list = Arrays.asList( Arrays.asList(1, 2), Arrays.asList(3));Warning: “Type safety: A generic array of List<Integer> is created for a varargsparameter”. But there was no way to fix it !In Java 7: No more warning, because Arrays.asList() is annotated: @SafeVarargs public static <T> List<T> asList(T... a) { return new ArrayList<>(a); } • The same was done to some other “safe” methods in the JDK that take generic varargs parameters. • The annotation can also be used for similar methods in your code.
  11. 11. Oliver Doepner - Java Lunch & Learn 2012 -Multi-catchvoid something() throws IOException, SQLException {};Java 6: Java 7:void blah() { void blah() { try { try { something(); something(); } catch (IOException e) { } catch (IOException | handle(e); SQLException e) { } catch (SQLException e) { handle(e); handle(e); } } }}Multi-catch implementation details • The catch parameter is automatically final • The catch block is not duplicated in the resulting bytecode
  12. 12. Oliver Doepner - Java Lunch & Learn 2012 -Try-with-resourcesJava 6:String firstLine(String path) throws IOException { BufferedReader br = null; try { br = new BufferedReader(new FileReader(path)); return br.readLine(); } finally { if (br != null) { • Multiple resources can be declared br.close(); • closing is done automatically, in reverse order } } • catch / finally blocks possible, executed after closing} • Suppressed exceptions: Throwable.getSuppressed() • Complex: Catching implicit / suppressed exceptionsJava 7:String firstLine(String path) throws IOException { try (BufferedReader br = new BufferedReader(new FileReader(path))) { return br.readLine(); Criticism: This could be implemented as a concise API using } closures, instead of a complex language (=compiler) feature.}
  13. 13. Oliver Doepner - Java Lunch & Learn 2012 -More precise re-throwHow would you do something like this in Java 6 ?JarFile retrieve(URL url) throws IOException { Path temp = Files.createTempFile("jar_cache", null); try (InputStream in = url.openStream()) { Files.copy(in, temp, REPLACE_EXISTING); return new JarFile(temp.toFile()); } catch (Throwable t) { Files.delete(temp); throw t; }} • In Java 6 the method would have to declare throws Throwable • Compiler analyzes which exception the try block can actually throw • Ideal for cleanup operations required if anything went wrong • The exception variable must not be assigned to (“effectively final”)
  14. 14. Oliver Doepner - Java Lunch & Learn 2012 -Revised File I/O (“NIO.2”)Built around the java.nio.Path and java.nio.Files classesPrevious mechanism, built around the java.io.File class, still availableComprehensive and extensible support for file metadata (permissions, owner, attributes)Proper support for symbolic linksScalable file I/O (all operation scale up to large directories, files and file systems)Behavior is consistent across platformsSupport for walking the file treeSearching the file system (PathMatcher API)Watching a directory for changes (WatchService, FileVisitor)
  15. 15. Oliver Doepner - Java Lunch & Learn 2012 -Corrected behaviourInteresting caveats fromhttp://www.oracle.com/technetwork/java/javase/compatibility-417013.html- Precise rethrow can cause source incompatibility (unreachable code)- Insertion of invalid element into TreeMap always throws NPE or ClassCastException- Changes in most specific varargs method selection- Compiler No Longer Allows Access to Private Members of Type Variables- Updated sort behavior for Arrays and Collections may throw anIllegalArgumentException- java.io.File.setReadOnly and setWriteable Methods Have New Behavior- Order of Methods returned by Class.getMethods can vary

×