Your SlideShare is downloading. ×
0
Upgrading to Java 7
Upgrading to Java 7
Upgrading to Java 7
Upgrading to Java 7
Upgrading to Java 7
Upgrading to Java 7
Upgrading to Java 7
Upgrading to Java 7
Upgrading to Java 7
Upgrading to Java 7
Upgrading to Java 7
Upgrading to Java 7
Upgrading to Java 7
Upgrading to Java 7
Upgrading to Java 7
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×
Saving this for later? Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime – even offline.
Text the download link to your phone
Standard text messaging rates apply

Upgrading to Java 7

390

Published on

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

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

Published in: Technology
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
390
On Slideshare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
7
Comments
0
Likes
1
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide

Transcript

  • 1. Oliver Doepner - Java Lunch & Learn 2012 - Upgrading to Java 7 http://doepner.net/ Presentation by Oliver Doepner Halifax 2012
  • 2. Oliver Doepner - Java Lunch & Learn 2012 -Agenda 1) Why upgrade? 2) Java 7 code examples 3) Corrected behaviours
  • 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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

×