new syntax elements of java 7
DESCRIPTION
Max Ramos, Oracle Certified Professional & Associate Software Engineer of Orange and Bronze Software Labs, discusses the new syntax elements of Java 7. www.orangeandbronze.comTRANSCRIPT
Java 7Max RamosAssociate Software Engineer, Orange & Bronze Software LabsOracle Certified Professional (Java SE 6 Programmer)
Overview
Binary Literals Underscore in Numerical Literals String in switch statement Diamond operator Multi-catch Try-with-resources
Binary Literals
Before Java 7
int decimal = 100;
int octal = 010; // decimal 8
int hexadecimal = 0x1f; // decimal 31
In Java 7
int b = 0b100; // decimal 2
or
int b = 0B100;
Underscore in numerical literals
Before Java 7
long largeNumber = 94158725;
long manyZeroes = 100000000;
In Java 7
long largeNumber = 94_158_725;
long manyZeroes = 100_000_000;
In Java 7
int i = 1000;
int j = 1_000;
if (I == j) { // true
}
or
If (1000 == 1_000) { // true
}
String in switch statement
Before Java 7
if (size.equals(“Short”)) {
// do something
} else if (size.equals(“Tall”)) {
// do something
} else if (size.equals(“Grande”)) {
// do something
} else if (size.equals(“Venti”)) {
// do something
} else {
// do something
}
In Java 7
switch (size) {
case “Short”: // do something
case “Tall”: // do something
case “Grande”: // do something
case “Venti”: // do something
default: // do something
}
Diamond operator
Before Java 7
List<String> list = new ArrayList<String>();
Set<Integer> set = new HashSet<Integer>();
Map<String, Object> map = new HashMap<String, Object>();
In Java 7
List<String> names = new ArrayList<>();
Set<Integer> count = new HashSet<>();
Map<String, Object> map = new HashMap<>();
Multi-catch
Before Java 7
try {
// do something that might throw an exception
} catch (ParseException e) {
// do something
} catch (IOException e) {
// do that same thing again
}
In Java 7
try {
// do something that might throw an exception
} catch (ParseException | IOException e) {
// do something
}
Try-with-resources
Before Java 7
public int methodName(String path) throws IOException {
FileReader fr = new FileReader(path);
try {
return fr.read()
} finally {
if (fr != null)
fr.close();
}
}
In Java 7
public int methodName(String path) throws IOException {
try (FileReader fr = new FileReader(path)){
return fr.read()
}
}
In Java 7
public void methodName(String path) throws IOException {
try (
FileReader fr = new FileReader(path);
FileWriter fw = new FileWriter(“out.txt”)
){
int i = fr.read();
fw.write(i);
}
}
About Orange & Bronze Software Labs
• Filipino software development company specializing in Java technology
• Consulting, outsourcing, and offshore product development services using Open Source technologies, with a specialization in the Spring and Grails frameworks
• Enterprise solutions with Google enterprise products and business intelligence solutions with the Pentaho BI Suite
• Offers Java, Agile and Android training courses
www.orangeandbronze.com
End