java 28 - 6 JDK7的新特性

JDK7的新特性:

  1. 二进制字面量
  2. 数字字面量可以出现下划线
  3. switch 语句可以用字符串
  4. 泛型简化
  5. 异常的多个catch合并
  6. try-with-resources 语句

二进制字面量

JDK7开始,终于可以用二进制来表示整数(byte,short,int和long)。

使用二进制字面量的好处是,可以使代码更容易被理解。语法非常简单,只要在二进制数值前面加 0b或者0B

举例:

int x = ob110110

 

数字字面量可以出现下划线

为了增强对数值的阅读性,如我们经常把数据用逗号分隔一样。JDK7提供了_对数据分隔。

  举例:

i  nt x = 100_1000;

注意事项:

  •   不能出现在进制标识和数值之间
  •   不能出现在数值开头和结尾
  •   不能出现在小数点旁边

 

try-with-resources 语句

格式:

  try(必须是java.lang.AutoCloseable的子类对象){…}

好处:

  • 资源自动释放,不需要close()了
  • 把需要关闭资源的部分都定义在这里就ok了
  • 主要是流体系的对象是这个接口的子类(看JDK7的API)

 

代码举例:

 1 public class Demo {
 2     public static void main(String[] args) {
 3         // 二进制字面量
 4         int x = 0b100101;
 5         System.out.println(x);
 6         // 数字字面量可以出现下划线
 7         int y = 1_1123_1000;
 8         // 不能出现在进制标识和数值之间
 9         int z = 0x111_222;
10         // 不能出现在数值开头和结尾
11         int a = 0x11_22;
12         // 不能出现在小数点旁边
13         double d = 12.3_4;
14         // switch 语句可以用字符串。之前用过
15         // 泛型简化
16         ArrayList<String> array = new ArrayList<>();
17         // 异常的多个catch合并
18         method();
19     }
20 
21     private static void method() {
22         // try-with-resources 语句
23         // try(必须是java.lang.AutoCloseable的子类对象){…}
24 
25         try {
26             FileReader fr = new FileReader("a.txt");
27             FileWriter fw = new FileWriter("b.txt");
28             int ch = 0;
29             while ((ch = fr.read()) != -1) {
30                 fw.write(ch);
31             }
32             fw.close();
33             fr.close();
34         } catch (IOException e) {
35             e.printStackTrace();
36         }
37 
38         // 改进版的代码
39         try (FileReader fr = new FileReader("a.txt");
40                 FileWriter fw = new FileWriter("b.txt");) {
41             int ch = 0;
42             while ((ch = fr.read()) != -1) {
43                 fw.write(ch);
44             }
45         } catch (IOException e) {
46             e.printStackTrace();
47         }
48     }
49 }

 

posted @ 2016-10-17 20:17  卡拉瓦  阅读(249)  评论(0编辑  收藏  举报