1. switch中添加对String类型的支持(Strings in switch Statements)
Java7之前,代码中只能在switch中只用number或enum;在Java7中,可以使用String。参考如下代码:
import java.util.*; public class MyDemo { public static void main(String args[]) { String choice = "Car"; switch (choice) { case "Car": System.out.println("Your choice is Car"); break; case "Money": System.out.println("Your choice is Money"); break; default: System.out.println("I don't know your choice"); break; } } }
2. 增加二进制表示(Binary Literals)
3. 数字字面量下划线支持(Underscores in Numeric Literals)
Java7之前,Java支持十进制(123)、八进制(0123)、十六进制(0X12AB);现在,Java7增加二进制表示(0B11110001、0b11110001)。
Java7同时支持在数字中间增加'_'作为分隔符,以增加可读性。参考如下代码:
public class MyDemo { public static void main(String args[]) { int binary = 0b0101001_1001; System.out.println("binary is :"+binary); } }
4. 异常处理,捕获多个异常(Catching Multiple Exception Types and Rethrowing Exceptions with Improved Type Checking)
参考如下代码:
import java.io.*; public class MyDemo { public void testMe() { try { // 输入整型数据错误 Integer.parseInt("haha"); // 文件不存在? File file = new File("D:\LibAntiPrtSc_INFORMATION.log"); BufferedReader in = new BufferedReader(new FileReader(file)); String str; while ((str = in.readLine()) != null) { System.out.println(str); } } catch (NumberFormatException | IOException e) { e.printStackTrace(); } } public static void main(String args[]) { new MyDemo().testMe(); } }
5. 泛型实例化类型自动推断(Type Inference for Generic Instance Creation)
在Java7之前,这样写的泛型代码:
Map<String, List<String>> myMap = new HashMap<String, List<String>>();
在Java7,以及之后,可以这样写:
Map<String, List<String>> myMap = new HashMap<>();
这个<>被叫做diamond(钻石)运算符,Java 7后这个运算符从引用的声明中推断类型。
6. 自动资源管理(The try-with-resources Statement)
Java中某些资源是需要手动关闭的,如InputStream,Writes,Sockets,Sql classes等。这个新的语言特性允许try语句本身申请更多的资源,这些资源作用于try代码块,并自动关闭。Java7之前的代码:
static String readFirstLineFromFileWithFinallyBlock(String path) throws IOException { BufferedReader br = new BufferedReader(new FileReader(path)); try { return br.readLine(); } finally { if (br != null) br.close(); } }
在Java7,以及之后的版本,可以这样写:
static String readFirstLineFromFile(String path) throws IOException { try (BufferedReader br = new BufferedReader(new FileReader(path))) { return br.readLine(); } }
7. Improved Compiler Warnings and Errors When Using Non-Reifiable Formal Parameters with Varargs Methods
这块还没看,待更新。
文章参考:
https://docs.oracle.com/javase/7/docs/technotes/guides/language/enhancements.html#javase7