1. 程式人生 > 其它 >Java重溫學習筆記,Java7新特性

Java重溫學習筆記,Java7新特性

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