Java7/8/9语法新特性
Java7
Java7的新特性是相对于Java6而言的,增加的特性如下:
二进制变量的表示,支持将整数类型用二进制来表示,用0b开头。
// 所有整数 int, short,long,byte都可以用二进制表示
// An 8-bit 'byte' value:
byte aByte = (byte) 0b00100001;
// A 16-bit 'short' value:
short aShort = (short) 0b1010000101000101;
// Some 32-bit 'int' values:
intanInt1 = 0b10100001010001011010000101000101;
intanInt2 = 0b101;
intanInt3 = 0B101; // The B can be upper or lower case.
// A 64-bit 'long' value. Note the "L" suffix:
long aLong = 0b1010000101000101101000010100010110100001010001011010000101000101L;
// 二进制在数组等的使用
final int[] phases = { 0b00110001, 0b01100010, 0b11000100, 0b10001001,
0b00010011, 0b00100110, 0b01001100, 0b10011000 };
Switch语句支持string类型
switch (dayOfWeekArg) {
case "Monday":
typeOfDay = "Start of work week";
break;
case "Tuesday":
case "Wednesday":
case "Thursday":
typeOfDay = "Midweek";
break;
case "Friday":
typeOfDay = "End of work week";
break;
case "Saturday":
case "Sunday":
typeOfDay = "Weekend";
break;
default:
throw new IllegalArgumentException("Invalid day of the week: " + dayOfWeekArg);
}
Try-with-resource语句
注意:实现java.lang.AutoCloseable接口的资源都可以放到try中,跟final里面的关闭资源类似; 按照声明逆序关闭资源 ;Try块抛出的异常通过Throwable.getSuppressed获取
try (java.util.zip.ZipFile zf = new java.util.zip.ZipFile(zipFileName);
java.io.BufferedWriter writer = java.nio.file.Files
.newBufferedWriter(outputFilePath, charset)) {
// Enumerate each entry
for (java.util.Enumeration entries = zf.entries(); entries
.hasMoreElements();) {
// Get the entry name and write it to the output file
String newLine = System.getProperty("line.separator");
String zipEntryName = ((java.util.zip.ZipEntry) entries
.nextElement()).getName() + newLine;
writer.write(zipEntryName, 0, zipEntryName.length());
}
}
Catch多个异常
public static void main(String[] args) throws Exception {
try {
testthrows();
} catch (IOException | SQLException ex) {
throw ex;
}
}
public static void testthrows() throws IO