一、二進制數字表達方式
原本整數(以60為例)能夠用十進制(60)、八進制(074)、十六進制(0x3c)表示,唯獨不能用二進制表示(111100),Java 7 彌補了這點。
1 public class BinaryInteger 2 { 3 public static void main(String[] args) { 4 int a = 0b111100; // 以 0b 開頭 5 System.out.println(a); //輸出60 6 } 7 }
二、使用下划線對數字進行分隔表達
原本表示一個很長的數字時,會看的眼花繚亂(比如1234567),Java 7 允許在數字間用下划線分隔(1_234_567),為了看起來更清晰。
1 public class UnderscoreNumber 2 { 3 public static void main(String[] args) { 4 int a = 1_000_000; //用下划線分隔整數,為了更清晰 5 System.out.println(a); 6 } 7 }
三、switch 語句支持字符串變量
原本 Switch 只支持:int、byte、char、short,現在也支持 String 了。
1 public class Switch01 2 { 3 public static void main(String[] args) { 4 String str = "B"; 5 switch(str) 6 { 7 case "A":System.out.println("A");break; 8 case "B":System.out.println("B");break; 9 case "C":System.out.println("C");break; 10 default :System.out.println("default"); 11 } 12 } 13 }
四、泛型的“菱形”語法
原本創建一個帶泛型的對象(比如HashMap)時:
- Map<String,String> map = new HashMap<String,String>();
很多人就會抱怨:“為什么前面聲明了,后面還要聲明!”。Java 7 解決了這點,聲明方式如下:
- Map<String,String> map = new HashMap<>();
五、自動關閉資源的try
原本我們需要在 finally 中關閉資源,現在 Java 7 提供了一種更方便的方法,能夠自動關閉資源:
- 將try中會打開的資源(這些資源必須實現Closeable或AutoCloseable)聲明在圓括號內。
1 import java.io.*; 2 public class Try01 3 { 4 public static void main(String[] args) { 5 try( 6 FileInputStream fin = new FileInputStream("1.txt"); // FileNotFoundException,SecurityException 7 ) 8 { 9 fin.read(); //拋 IOException 10 } 11 catch(IOException e) //多異常捕捉 12 { 13 e.printStackTrace(); 14 } 15 } 16 }
六、多異常捕捉
如果在try語句塊中可能會拋出 IOException 、NumberFormatException 異常,因為他們是檢驗異常,因此必須捕捉或拋出。如果我們捕捉他且處理這兩個異常的方法都是e.printStackTrace(),則:
1 try 2 { 3 } 4 catch(IOException e) 5 { 6 e.printStackTrace(); 7 } 8 catch(NumberFormatException e) 9 { 10 e.printStackTrace(); 11 }
Java 7 能夠在catch中同時聲明多個異常,方法如下:
1 try 2 { 3 } 4 catch(IOException | NumberFormatException e) 5 { 6 e.printStackTrace(); 7 }
七、增強型throws聲明
原本如果在try中拋出 IOException,以catch(Exception e)捕捉,且在catch語句塊內再次拋出這個異常,則需要在函數聲明處:throws Exception,而不能 throws IOException,因為Java編譯器不知道變量e所指向的真實對象,而Java7修正了這點。
1 import java.io.*; 2 public class Throws01 3 { 4 public static void main(String[] args) throws FileNotFoundException{ 5 try 6 { 7 FileInputStream fin = new FileInputStream("1.txt"); 8 } 9 catch(Exception e) //Exception e = new FileNotFoundException(); 10 { 11 throw e; 12 } 13 } 14 }
