Friday, 2 May 2014

Java 7 Features You (Probably) Didn't Hear About

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:
...

}
NOTE:-
Did you know it produces generally more efficient byte codes than an if-then-else statement? Case Sensitive!


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<>());


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;
}
}
NOTE:-
•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.


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 

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.


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);


Java NIO.2 Directories


DirectoryStream iterate over entries

Scales to large directories

Uses less resources

Smooth out response time for remote file systems

Implements Iterableand Closeablefor productivity
Filtering support

Build-in support for glob, regex and custom filters
Path srcPath = Paths.get(“/home/fred/src”);
try (DirectoryStream<Path> dir =
srcPath.newDirectoryStream(“*.java”)) {
for (Path file : dir)
System.out.println(file.getName());

}


Standardize Nimbus Look and Feel

Better than Metal for cross platform look-and-feel
Introduced in Java SE 6u10, now part of Swing
Not the default L&F
Scalable Java 2D impl


Mixing of AWT and Swing –Works*

As of 6u12 and 7u1, some caveats for scroll bars


JDBC 4.1

Try-with-resources statement to automatically close resources of typeConnection,ResultSet, andStatement
try (Statement stmt = con.createStatement()) { // ... }
RowSet 1.1 introduces RowSetFactoryand RowSetProvider
//Factory options (impl) set on cmd line or metainf
myRowSetFactory = RowSetProvider.newFactory();
jdbcRs = myRowSetFactory.createJdbcRowSet();
jdbcRs.setUrl("jdbc:myDriver:myAttribute"); //etc
jdbcRs.setCommand("select COF_NAME, SUP_ID, PRICE, SALES, TOTAL from COFFEES");

jdbcRs.execute();


Draggable Applet Decoration

Applet decoration settings apply equally to in browser and out of browser launches –borderless, etc.


JavaDoc Improvements in Java 7

Section 508 accessibility guidelines
Captions, headings, etc.
Previously, JavaDoc wrote to an OutputStream on the fly meaning it built the document sequentially, imposing limitations
Now uses internal “HTMLTree” classes
Generates compliant HTML
Allows for more advancements in the future
Removes limitation of only being able to execute only once in any VM
Was fine when used as a command line tool
Continuous build, etc, made it necessary to address this!


The preceding is intended to outline our general product direction. It is intended for information purposes only, and may not be incorporated into any contract. It is not a commitment to deliver any material, code, or functionality, and should not be relied upon in making purchasing decisions.The development, release, and timing of any features or functionality described for Oracle’s products remains at the sole discretion of Oracle.

1 comment: