Java 7 Features
Binary Literals
int mask = 0b101010101010;
aShort = (short)0b1010000101000101;
long aLong = 0b1010000101000101101000010100010110100001010001011010000101000101L;
Underscores in Numeric Literals
• Valid:
int mask = 0b1010_1010_1010;
long big = 9_223_783_036_967_937L;
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_BFFE;
• Invalid:
float pi1 = 3_.1415F; float pi2 = 3._1415F;
long ssn = 999_99_9999_L;
int x1 = _52; int x1 = 52_;
int x2 = 0_x52; int x2 = 0x_52;
Strings in Switch Statements
int monthNameToDays(String s, int year) {
switch(s) {
case "April": case "June":
case "September": case "November":
return 30;
case "January": case "March":
case "May": case "July":
case "August": case "December":
return 31;
case "February”:
...
default:
...
}
}
Did you know it produces generally more efficient byte codes than an if-then-else statement? Case Sensitive!
Automatic Resource Management
try (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 superinterfacejava.lang.AutoCloseable
• All AutoCloseable(throws Exception) and by extension java.io.Closeable(throws IOException) types useable with try-with-resources
• Anything with a void close()method is a candidate
• JDBC 4.1 retrofitted as AutoCloseabletoo
Suppressed Exceptions
java.io.IOException
at Suppress.write(Suppress.java:19)
at Suppress.main(Suppress.java:8)
Suppressed: java.io.IOException
atSuppress.close(Suppress.java:24)
atSuppress.main(Suppress.java:9)
Suppressed: java.io.IOException
at Suppress.close(Suppress.java:24)
at Suppress.main(Suppress.java:9)
Throwable.getSupressed(); // Returns Throwable[]
Throwable.addSupressed(aThrowable);
Multi-Catch
try {
...
}
catch (ClassCastException e) {
doSomethingClever(e);
throw e;
}
catch(InstantiationException | NoSuchMethodException | InvocationTargetException e) {
// Useful if you do generic actions
log(e);
throw e;
}
More Precise Rethrow
public void foo(String bar)
throws FirstException, SecondException
{
try {
// Code that may throw both
// FirstException and SecondException
}
catch (Exception e) {
throw e;
}
}
• Prior to Java 7, this code would not compile, the types in throws would have to match the types in catch –foo would have to “throws Exception”
• Java 7 adds support for this as long as try block calls all the exceptions in the throws clause, that the variable in the catch clause is the variable that is rethrown and the exceptions are not caught by another catch block.
Diamond Operator works many ways…
With diamond (<>) compiler infers type…
List<String>strList = new ArrayList<>();
OR
List<Map<String, List<String>>strList = new ArrayList<>();
OR
Foo<Bar> foo = new Foo<>();
foo.mergeFoo(new Foo<>());
Varargs Warnings –Erasure
class Test
{
public static void main(String... args)
{
List<List<String>> monthsInTwoLanguages = Arrays.asList(Arrays.asList("January","February"),
Arrays.asList("Gennaio","Febbraio" ));
}
}
Test.java:7: warning:
[unchecked] unchecked generic array creation
for varargs parameter of type List<String>[]
Arrays.asList(Arrays.asList("January",
^
1 warning
@SuppressWarnings(value = “unchecked”) // at call
@SafeVarargs // at declaration
Java NIO.2 –File Navigation Helpers
Two key navigation Helper Types:
• Class java.nio.file.Paths
Exclusively static methods to return a Path by converting a string or Uniform Resource Identifier (URI)
• Interface java.nio.file.Path
Used for objects that represent the location of a file in a file system, typically system dependent.
Typical use case:
Use Paths to get a Path. Use Files to do stuff.
//Make a reference to a File
Path src = Paths.get(“/home/fred/readme.txt”);
Path dst = Paths.get(“/home/fred/copy_readme.txt”);
//Make a reference to a path
Path src = Paths.get(“/home/fredSRC/”);
Path dst = Paths.get(“/home/fredDST/”);
//Navigation /home/fredSRC -> /home/fredSRC/tmp
Path tmpPath = src.resolve(“tmp”);
//Create a relative path from src -> ..
Path relativePath = tmpPath.relativize(src);
// Convert to old File Format for your legacy apps
File file = aPathPath.toFile();
Java NIO.2 Features –Files Helper Class
• Class java.nio.file.Files
• Exclusively static methods to operate on files, directories and other types of files
• Files helper class is feature rich:
• Copy
• Create Directories
• Create Files
• Create Links
• Use of system “temp” directory
• Delete
• Attributes –Modified/Owner/Permissions/Size, etc.
• Read/Write
Files.move(src, dst, StandardCopyOption.ATOMIC_MOVE);
Files.copy(src, dst, StandardCopyOption.COPY_ATTRIBUTES, StandardCopyOption.REPLACE_EXISTING);
Comments
Post a Comment