Java Reference
In-Depth Information
Try With Resources
Another great simplification for proper error handling! You can now create resources (I/O
Streams/Writers, JDBC Connections, …) as the argument of a try statement and have them
closed automatically. The resource must implement the (new for this purpose) AutoCloseable
interface. Many standard classes have been modified to implement AutoCloseable to support
this.
try (BufferedReader is = new BufferedReader(new FileReader(fileName))) {
String line;
while ((line = is.readLine()) != null) {
System.out.println(line); }
} catch (IOException e) {
handleError("Problem reading " + fileName, e);
} // No finally needed, no close needed - it's all done automatically!
Type Inference for Generics (Diamond Operator, <>)
Java 5 introduced Generic Types, as described in Java 5 generic types . For example, to create
a List of String s without any warning messages, you might write:
List<String> names = new ArrayList<String>();
Java 7 brings “Type Inference” for Generic Types. Instead of having to repeat the type para-
meter from the declaration in the definition, omit it and just put <>. The preceding list of
strings can be rewritten as:
List<String> names = new ArrayList<>();
Java 7 String Switch
This long-awaited feature lets you replace a series of if statements using string comparisons,
by a single switch statement; i.e., you can now use Strings as case labels:
String input = getStringFromSomewhere();
switch(input) {
case "red":
System.out.println("Stop!");
break;
case "amber": case "yellow":
Search WWH ::




Custom Search