jdk7新特性学习笔记
从网络down了视频看,记录下学过的东西。
1.二进制字面量
JDK7开始,可以用二进制来表示整数(byte,short,int和long),语法:在二进制数值前面加 0b或者0B
例如:int x = 0b1111
2.数字字面量可以出现下划线
为了增强对数值的阅读性,如我们经常把数据用逗号分隔一样。JDK7提供了_对数据分隔。
举例:
int x = 100_1000;
注意事项:
不能出现在进制标识和数值之间
不能出现在数值开头和结尾
不能出现在小数点旁边
举例:
int x = 100_1000;
注意事项:
不能出现在进制标识和数值之间
不能出现在数值开头和结尾
不能出现在小数点旁边
3.switch 语句可以用字符串
略
4.泛型简化
ArrayList<String> array = new ArrayList<>();
5.异常的多个catch合并
catch (IOException ex) {
logger.error(ex);
throw new MyException(ex.getMessage());
catch (SQLException ex) {
logger.error(ex);
throw new MyException(ex.getMessage());
}catch (Exception ex) {
logger.error(ex);
throw new MyException(ex.getMessage());
}
可以改为:
catch(IOException | SQLException | Exception ex){
logger.error(ex);
throw new MyException(ex.getMessage());
}
6.try-with-resources 语句
// try-with-resources 语句
// try(必须是java.lang.AutoCloseable的子类对象){…}
try {
FileReader fr = new FileReader("a.txt");
FileWriter fw = new FileWriter("b.txt");
int ch = 0;
while ((ch = fr.read()) != -1) {
fw.write(ch);
}
fw.close();
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
// 改进版的代码
try (FileReader fr = new FileReader("a.txt");
FileWriter fw = new FileWriter("b.txt");) {
int ch = 0;
while ((ch = fr.read()) != -1) {
fw.write(ch);
}
} catch (IOException e) {
e.printStackTrace();
}
}
自动关闭流了。注意,try()中的类必须是java.lang.AutoCloseable的子类对象。
这个接口来自jdk1.7,io操作的类都实现了此接口。