Wednesday 25 November 2015

Code examples for new features in Java 1.7



Automatic Resource Management

this:
BufferedReader br = new BufferedReader(new FileReader(path));
try {
   return br.readLine();
} finally {
   br.close();
}
becomes:
try (BufferedReader br = new BufferedReader(new FileReader(path)) {
   return br.readLine();
}
You can declare more than one resource to close:
try (
   InputStream in = new FileInputStream(src);
   OutputStream out = new FileOutputStream(dest))
{
 // code
}

Underscores in numeric literals

int one_million = 1_000_000;

Strings in switch

String s = ...
switch(s) {
 case "quux":
    processQuux(s);
    // fall-through
case "foo":
  case "bar":
    processFooOrBar(s);
    break;
case "baz":
     processBaz(s);
    // fall-through
default:
    processDefault(s);
    break;
}

Binary literals

int binary = 0b1001_1001;

Improved Type Inference for Generic Instance Creation

Map<String, List<String>> anagrams = new HashMap<String, List<String>>();
become:
Map<String, List<String>> anagrams = new HashMap<>();

Better exception handling

this:
} catch (FirstException ex) {
     logger.error(ex);
     throw ex;
} catch (SecondException ex) {
     logger.error(ex);
     throw ex;
}
become:
} catch (FirstException | SecondException ex) {
     logger.error(ex);
    throw ex;
}

No comments:

Post a Comment