Java7 New Features and Code Examples


Published on

Java 7 New Features and Code Examples

Published in: Technology, Education

Java7 New Features and Code Examples

  1. 1. Java 7 New Features & Code Examples Naresh Chintalcheru
  2. 2. Numeric Literals with Underscores int thousand = 1_000; int million = 1_000_000; //1000000 (one million) double d1 = 1000_000_.0d long a1 = 0b1000_1010_0010_1101_1010_0001_0100_0101L; Imagine counting tens of zero’s ?. No need to strain eyes or manual errors with Underscores
  3. 3. Bracket Notation for Collection Old-Way Collection<String> c = new ArrayList(); c.add(“one”); c.add(“two”); c.add(“ten”); New-Way Collection<String> c = new ArrayList {“one”, “two”, “ten”};
  4. 4. try-with-resource Old-Way BufferedReader br = null; try { br = new BufferedReader(new FileReader(path)); return br.readLine(); }catch(IOException ioEx) {} finally { try{ br.close(); }catch(IOException ioEx) {} }
  5. 5. try-with-resource • The File, JDBC, MQ, LDAP & Mail resource connections will be opened & closed • The finally block is used to make sure the resources are closed • Have another try-catch for closing the resources
  6. 6. try-with-resource New-Way try (BufferedReader br = new BufferedReader(new FileReader(path)); BufferedWriter bw = new BufferedWriter(new FileWriter(path)); ){ //File code } catch(IOException ioEx) { } With Java7 try-with-resource the resources BufferedReader & BufferedWriter implements java.lang. AutoCloseable and will be closed automatically
  7. 7. try-with-resource New-Way try (Statement stmt = con.createStatement()) { ResultSet rs = stmt.executeQuery(query); while ( String coffeeName = rs.getString("Name”); } catch (SQLException e) { } With Java7 try-with-resource the resource javax.sql. Statement implements java.lang.AutoCloseable and will be closed automatically
  8. 8. Multi-Catch Old-Way try { //statements } catch (ExceptionOne ex) { logger.error(ex); throw ex; } catch (ExceptionTwo ex) { logger.error(ex); throw ex; } catch (ExceptionThree ex) { logger.error(ex); throw ex; }
  9. 9. Multi-Catch New-Way try { //statements } catch (ExceptionOne | ExceptionTwo | ExceptionThree ex) { logger.error(ex); throw ex; } Clean code with multiple exceptions in one Catch block
  10. 10. Final Rethrow void process() throws IOException, SQLException try { //statements } catch (final throw ex; } Throwable ex) { New precise rethrow feature which lets catch and throw the base exception while still throwing the precise exception from the calling method
  11. 11. String in Switch Statement Finally ☺ ☺ ☺ String day; switch (day) { case "Monday": break; case "Tuesday": case "Sunday": typeOfDay = "Weekend"; break; default: throw new IllegalArgumentException("Invalid"); } .
  12. 12. Simple Generic Instance Old-Way List<String> strings = new ArrayList<String>(); Map<String, List<String>> myMap = new HashMap<String, List<String>>(); New-Way (Simple) List<String> strings = new ArrayList<>(); Map<String, List<String>> myMap = new HashMap<>(); .
  13. 13. Java.nio.file* (NIO2) java.nio.file.Files java.nio.file.Path java.nio.file.Paths Paths and Path - File locations/names Files - Operations on file content FileSystem – provides file services File.toPath() method, Lets older code interact with the new java.nio API .
  14. 14. Create File Symbolic Link java.nio.file.Files.createSymbolicLink() createSymbolicLink() – creates a symbolic link, if supported by the file system public static Path createSymbolicLink(Path link, Path target, FileAttribute<?>... attrs) throws IOException .
  15. 15. Path, Files & Scanner final static Charset ENCODING = StandardCharsets.UTF_8; List<String> readFile(String aFileName) throws IOException { Path path = Paths.get(aFileName); return Files.readAllLines(path, ENCODING); //Read List } void readFile(String aFileName) throws IOException { Path path = Paths.get(aFileName); try (Scanner scanner = new Scanner(path,{ while (scanner.hasNextLine()){ log(scanner.nextLine()); //Read String Line } }} .
  16. 16. Path & Files To Write final static Charset ENCODING = StandardCharsets.UTF_8; void writeFile(List<String> aLines, String aFileName) throws IOException { Path path = Paths.get(aFileName); Files.write(path, aLines, ENCODING); //Write using List } void writeFile(String aFileName, List<String> aLines) throws IOException { Path path = Paths.get(aFileName); try (BufferedWriter writer = Files.newBufferedWriter(path, ENCODING)){ for(String line : aLines){ writer.write(line); //Write String line writer.newLine(); } }}.
  17. 17. File Change Notifications File Change Notifications with WatchService APIs private void watch() { Path path = Paths.get("C:Temptemp"); try { watchService = FileSystems.getDefault().newWatchService(); path.register(watchService, ENTRY_CREATE, ENTRY_DELETE, } catch (IOException e) { System.out.println("IOException"+ e.getMessage()); } } ENTRY_MODIFY);
  18. 18. Streaming & Channel-based I/O • A stream is a contiguous sequence of data. Stream IO acts on a single character at a time, while channel IO works with a buffer for each operation. • These are supported by the Files class and Buffered IO is usually more efficient to be used in reading and writing data. • The java.nio.channels package's ByteChannel interface is a channel that can read and write bytes. • The SeekableByteChannel interface extends the ByteChannel interface to maintain a position within the channel. The position can be changed using seek type random IO operations.
  19. 19. Asynchronous Channel-based I/O Support for Asynchronous channel-based I/O functionality • AsynchronousFileChannel class is used for file manipulation operations that need to be performed in an asynchronous manner, the methods supporting the File write and read operations. • AsynchronousChannelGroup class provides a means of grouping asynchronous channels together in order to share resources. • Java.nio.file package's SecureDirectoryStream class provides support for more secure access to directories. However, the underlying operating system must provide local support for this class.
  20. 20. URLClassLoader Closing The URLClassLoader.close() method eliminates the problem of supporting updated implementations of the classes and resources loaded from a particular codebase, and in particular from JAR files.
  21. 21. URLClassLoader Closing URL url = new URL("file:foo.jar"); URLClassLoader loader = new URLClassLoader (new URL[] {url}); Class cl = Class.forName ("Foo", true, loader); Runnable foo = (Runnable) cl.newInstance();; loader.close (); // foo.jar gets updated somehow loader = new URLClassLoader (new URL[] {url}); cl = Class.forName ("Foo", true, loader); foo = (Runnable) cl.newInstance(); // run the new implementation of Foo; Eliminates Server restarts
  22. 22. JDBCRowSet The RowSetFactory interface and the RowSetProvider class, which enable you to create all types of row sets supported by the JDBC driver. RowSetFactory myRowSetFactory = RowSetProvider.newFactory(); JdbcRowSet jdbcRs = myRowSetFactory.createJdbcRowSet(); jdbcRs.setUrl("jdbc:driver:myAttribute"); jdbcRs.setUsername(username); jdbcRs.setPassword(password); jdbcRs.setCommand("select * from Emp"); jdbcRs.execute(); jdbcRs.moveToInsertRow(); jdbcRs.updateInt(“AGE", 0); jdbcRs.insertRow(); jdbcRs.last(); jdbcRs.deleteRow();
  23. 23. Varargs public class VarArgsJavav6 { public static void main(String[] args) { vaMethod("a", "b", "c"); } public void vaMethod(String... args) { for(String s : args) System.out.println(s); } } Automatically treats Method parameter as an Array
  24. 24. JVM G1 Garbage Collector • The Garbage-First (G1) garbage collector achieves high performance and pause time goals through several techniques • The G1 collector is a server-style garbage collector, targeted for multi-processor machines with large memories • Meets garbage collection (GC) pause time goals with high probability, while achieving high throughput.
  25. 25. Dynamic Language Support • Java is a static typed language to make it little bit more dynamic (long way to go) similar to dynamic typed languages like Ruby, Python & Clojure the new package java.lang. invoke is introduced • A new package java.lang.invoke includes classes MethodHandle, CallSite and others, has been created to extend the support of dynamic languages .
  26. 26. Java 7 Performance Improved String Performance Improved Array Performance Security Enhancements Support for Non-Java Languages - invokedynamic
  27. 27. References
  28. 28. Thank You