Diamond syntax

Map<String, List<String>> map = new HashMap<String, List<String>>();

Map<String, List<String>> map = new HashMap<>();

Exception multi-catch

package com.mrbool.java7.coin; import java.sql.*; public class MultiCatch { public static Connection connectToDatabase(String driver, String url, String user, String pwd) { Connection conn = null; try { Class.forName(driver); conn = DriverManager.getConnection(url, user, pwd); } catch (ClassNotFoundException ex) { System.out.println("Problems while creating a database connection. Check your settings!"); } catch (SQLException ex) { System.out.println("Problems while creating a database connection. Check your settings!"); } return conn; } }

package com.mrbool.java7.coin; import java.sql.*; public class MultiCatch { public static Connection connectToDatabase(String driver, String url, String user, String pwd) { Connection conn = null; try { Class.forName(driver); conn = DriverManager.getConnection(url, user, pwd); } catch (ClassNotFoundException | SQLException ex) { System.out.println("Problems while creating a database connection. Check your settings!"); } return conn; } }

Try with closeable resources

package com.mrbool.java7.coin; import java.io.*; public class TryWithResources { public static void copy(File src, File dst) { InputStream in = null; OutputStream out = null; try { in = new FileInputStream(src); out = new FileOutputStream(dst); byte[] buf = new byte[8192]; int n; while ((n = in.read(buf)) >= 0) out.write(buf, 0, n); } catch (FileNotFoundException | IOException ex) { System.out.println("Problems while copying: " + ex); } finally { if (in != null) try { in.close(); } catch (IOException ex) { System.out.println("Problems while copying: " + ex); } finally { if (out != null) try { out.close(); } catch (IOException ex) { System.out.println("Problems while copying: " + ex); } } } } }

package com.mrbool.java7.coin; import java.io.*; public class TryWithResources { public static void copy(File src, File dst) { try (InputStream in = new FileInputStream(src); OutputStream out = new FileOutputStream(dst);) { byte[] buf = new byte[8192]; int n; while ((n = in.read(buf)) >= 0) out.write(buf, 0, n); } catch (FileNotFoundException | IOException ex) { System.out.println("Problems while copying: " + ex); } } }

Strings in switch

Up until Java 6, only discrete primitive types (int, long, char, etc.) could be used in a switch command. However, it is very common to run into situations in which a String variable should be verified and, depending on its value, the program should produce a different result. For illustrative purposes, the class of Listing 5 contains a method that returns the number of days in a month, given the month's name. This is done through a series of chained if-else instructions.



Listing 5. Class that determines the number of days in a given month using chained if-else commands.

package com.mrbool.java7.coin; public class StringsImSwitch { public int daysInMonth(String month, int year) { if (month == null) throw new IllegalArgumentException("Specify the month!"); month = month.toLowerCase(); if (month.equals("april") || month.equals("june") || month.equals("september") || month.equals("november")) return 30; else if (month.equals("january") || month.equals("march") || month.equals("may") || month.equals("july") || month.equals("august") || month.equals("october") || month.equals("december")) return 31; else if (month.equals("february")) return ((year % 4 == 0 && year % 4 != 100) || (year % 400 == 0)) ? 29 : 28; else throw new IllegalArgumentException("Unknown month: " + month); } }



If instead of having the name of the month as an argument, the method received the number of the month (1-12), these chained if-else commands could be replaced by a switch statement, which has a more concise, easier to read syntax for situations like this. Starting from Java 7, however, it is also possible to use strings in switch, like shown in Listing 6.



Listing 6. Same code as in Listing 5, but using strings in switch.

package com.mrbool.java7.coin; public class StringsImSwitch { public int daysInMonth(String month, int year) { if (month == null) throw new IllegalArgumentException("Specify the month!"); month = month.toLowerCase(); switch (month) { case "april": case "june": case "september": case "november": return 30; case "january": case "march": case "may": case "july": case "august": case "october": case "december": return 31; case "february": return ((year % 4 == 0 && year % 4 != 100) || (year % 400 == 0)) ? 29 : 28; default: throw new IllegalArgumentException("Unknown month: " + month); } } }



Improved representation of literal values

To aid in the representation of binary numbers (for people that work with bit manipulation) and of numbers with many digits, Project Coin includes a small change in the syntax to improve the representation of numeric literals. Compare the examples of Listings 7 and 8.



Listing 7. Small program that illustrates bit manipulation and numbers with many digits.

package com.mrbool.java7.coin; import java.text.NumberFormat; import java.util.Locale; public class NumericLiterals { public static final int EXECUTE = 1; public static final int MODIFY = 2; public static final int READ = 4; public static void main(String[] args) { int permission = EXECUTE + READ; if ((permission & READ) != 0) System.out.println("Can read"); if ((permission & MODIFY) != 0) System.out.println("Can modify"); if ((permission & EXECUTE) != 0) System.out.println("Can execute"); long aBillion = 1000000000; NumberFormat nf = NumberFormat.getCurrencyInstance(); System.out.println(nf.format(aBillion)); } }



Listing 8. Same code as in Listing 7, but using the improved syntax for numeric literals.

package com.mrbool.java7.coin; import java.text.NumberFormat; import java.util.Locale; public class NumericLiterals { public static final int EXECUTE = 0b001; public static final int MODIFY = 0b010; public static final int READ = 0b100; public static void main(String[] args) { int permission = EXECUTE + READ; if ((permission & READ) != 0) System.out.println("Can read"); if ((permission & MODIFY) != 0) System.out.println("Can modify"); if ((permission & EXECUTE) != 0) System.out.println("Can execute"); long aBillion = 1_000_000_000; NumberFormat nf = NumberFormat.getCurrencyInstance(); System.out.println(nf.format(aBillion)); } }



Both use bit manipulation in the first part of the program, simulating an access control system. Permissions for read, modify and execute in systems like Linux are represented by three digit binary numbers, where the first digit represents reading permission, the second modifying permission and the third executing permission (e.g., 110 represents read and modify but not execute, 101 represents read and execute but not modify, and so forth).



In Listing 7, the way this was done up until Java 6, bits representing each type of permissions should be assigned in their decimal form – (001)2 = (1)10, (010)2 = (2)10 e (100)2 = (4)10 – however, starting from Java 7, we can use the binary representation of these numbers – 0b001, 0b010 e 0b100 – facilitating both writability and legibility of the code.



And for large numbers (be them integers, in any numeric base, or be them reals), Project Coin allows that underscores be used for separation, being ignored later by the compiler when reading the literal. For instance, it is customary to use commas to separate every three digits of numbers in the decimal base to make reading them easier, so in Listing 8 the value of the aBillion variable was also separated at each three digits, making this value much more legible than the one in Listing 7. For binary numbers, it is common to separate them at every byte (8 bits) or half a byte (4 bits).



Besides promoting all of these small changes to the syntax of the Java language, another objective of Project Coin was to apply all of these changes in the API of Java itself, which allowed developers to test these modifications in terms of performance and improvements in legibility and reliability of the code.

Project Coin is the codename given to JSR 334 – Small Enhancements tog the Java Programming Language. Started on December 2010 and approved on July 20, 2011, the changes proposed by Project Coin aim at: removing unnecessary code from the Java syntax in order to make Java source files more legible and increasing the productivity in development; encouraging developers to write more reliable code; and, at the same time, integrate well with past modifications (e.g., generics) and possible future modifications (e.g., Project Lambda) of the language.Under the guidance of Joe Darcy, from Oracle, the project started with a call for proposals opened to the whole Java community. Through a specific form, anyone could submit a proposal of change in the Java language. In the first month alone, more than 70 proposals were submitted.In the final version, six of these changes were selected. In order to make generic types easier to use, the project introduces the diamond syntax and reduces the number of warnings in the API. With the goal of improving error handling, the novelties are multi-catch for exceptions and try with closeable resources. Finally, to improve consistency and clarity of the language, Project Coin proposes the use of strings in switch statements and better representation of literal values.Until version 1.4, Java offered untyped collections (lists, sets, maps, etc.): any object could be placed in a collection and any element taken from a collection was referenced as an instance of, needing a cast to their original class (). Java 5 brought generic types to the Java language, making it possible to specify a collection of a specific type. This allowed the compiler and virtual machine to check that only objects of the specified class (or subclasses) were placed in the collection and, moreover, dismissed the need of casting the object to its specific class when it was obtained from the collection.However, the syntax for the utilization of generic types contains, most of the times, an unnecessary repetition. When the variable is declared and the instance is created on the same line, it was necessary to repeat the generic type in both operations. For instance:The line of code above declares a variable called map that provides mapping of strings to lists of strings. Then, it creates an object that implements theinterface – in this case, a– again determining that it should be a hash map of strings to lists of strings. In the vast majority of cases, the generic type at the right-hand side is exactly the same as the one at the left-hand side (also because inheritance rules for generic types are really complicated!). With Java 7, the definition of the generic type at the right-hand side can be omitted, leaving only the charactersThe above line of code does exactly the same as the previous one, but in a way that is much easier to read and to write.In some situations, a piece of code may throw multiple exceptions, but treat them all the same way. For instance,shows a class that has a method for the creation of a database connection. The part of the code that creates the connection can throw two exceptions:if the database driver is not found, andif the connection cannot be established for other reasons.A method that creates a database connection, treating two types of exception separately.Suppose, in this case, that the handling of the exceptions is the same: show an error message asking the user to check his settings and try again. In situations like this, the code can benefit from another improvement brought by Project Coin: exception multi-catch, as shown inSame class of Listing 1, but using exception multi-catch to deal with two types of exception in the same block.In the new code, both exceptions are specified in the same(as highlighted in bold), separating their names with the pipe symbol: |. Note that the same effect could have been obtained specifying an exception class that is superclass of both of these exceptions:. However, in this case the code would capture any subclass of(that is, all types of exception, including the) and not only the two that were specified inAnother enhancement that reduces considerably the amount of infrastructure code (sometimes referred to as “plumbing”) that has to be written in order to execute some kinds of operations in Java is the new try with closeable resources. As an example, see ina class that offers a method to copy the contents of a file into another.A method for file copying, demonstrating the excess of infrastructure code around the actual functionality.The five lines of code that actually realize the file copy are highlighted in bold, whereas the other 19 lines were written only to deal with possible exceptions. So many extra lines of code are needed because the operation that needs to be conducted in the finally block – closing the input and output streams – can themselves throw exceptions. In case one of the streams throws an exception when closing, we should still try to close the other stream. Resources that are not closed may not work properly (e.g., the file may not be completely copied) or occupy system resources, like, for instance, memory (more of a problem when the operation is in a loop, as resource consumption can grow to the point of overflowing the stack and the program will be terminated by the operating system).Java 7 solves the problem introducing try with closeable resources, as shown in. Thecommand can now receive as arguments objects that implement theinterface. Such objects must be initialized in the try command and will be automatically closed and disposed by the virtual machine at the end of the block. This way, we can reduce from 19 to three the number of lines of code for exception handling, and still guaranteeing that all resources that can be closed will be closed.Same code of Listing 3, but using try with closeable resources.