一、二进制字面量
二、数字字面量可以出现下划线
三、switch 语句可以用字符串
四、泛型简化
五、异常的多个catch合并
六、try-with-resources 语句
一、二进制字面量 <=返回目录
// 二进制字面量 int x = 0b100101; System.out.println(x); // 37
二、数字字面量可以出现下划线 <=返回目录
// 数字字面量可以出现下划线 int x = 1_000; int y = 1_1123_1000; int z = 1_2_3_4_5; System.out.println("x=" + x + ", y=" + y + ",z=" + z); // 不能出现在进制标识和数值之间 int a = 0b0000_0011; // 不能出现在数值开头和结尾 int b = 0x11_22; // 不能出现在小数点旁边 double c = 12.3_4; System.out.println("a=" + a + ", b=" + b + ",c=" + c);
三、switch 语句可以用字符串 <=返回目录
package com.oy.test; public class Test { public static void main(String[] args) { String key = "KEY_1"; String value = getValue(key); System.out.println("key=" + key + ", value=" + value); } private static String getValue(String key) { String value = ""; switch (key) { case "KEY_1": value += "格式错误"; break; case "KEY_2": value += "密码错误"; break; default: value += "系统错误"; break; } return value; } }
四、泛型简化 <=返回目录
// 菱形语法:泛型推断 List<String> list = new ArrayList<>();
五、异常的多个catch合并 <=返回目录
// jdk7之前的做法 private static void method() { String className = "com.oy.test.Person"; Class<?> clazz = null; try { clazz = Class.forName(className); Person p = (Person) clazz.newInstance(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } // jdk7之后,异常的多个catch合并 private static void method2() { String className = "com.oy.test.Person"; Class<?> clazz = null; try { clazz = Class.forName(className); Person p = (Person) clazz.newInstance(); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) { e.printStackTrace(); } }
六、try-with-resources 语句 <=返回目录
public static void main(String[] args) { method(); } // jdk7之前的做法 private static void method() { // try-with-resources 语句 // try(必须是java.lang.AutoCloseable的子类对象){…} FileReader fr = null; FileWriter fw = null; try { fr = new FileReader("d:/a.txt"); fw = new FileWriter("d:/b.txt"); int ch = 0; while ((ch = fr.read()) != -1) { fw.write(ch); } // int a = 1/0; // for test } catch (IOException e) { e.printStackTrace(); } finally { if (fw != null) { try { fw.close(); System.out.println("close fw..."); } catch (IOException e) { e.printStackTrace(); } } if (fr != null) { try { fr.close(); System.out.println("close fr ..."); } catch (IOException e) { e.printStackTrace(); } } } } // jdk7之后改进版的代码 private static void method2() { // try-with-resources 语句 // try(必须是java.lang.AutoCloseable的子类对象){…} try (FileReader fr = new FileReader("d:/a.txt"); FileWriter fw = new FileWriter("d:/b.txt");) { int ch = 0; while ((ch = fr.read()) != -1) { fw.write(ch); } // int a = 1/0; // for test } catch (IOException e) { e.printStackTrace(); } }