新浪微博 Github

Java 7 语法新特性

一、二进制数字表达方式

 原本整数(以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 }
posted @ 2013-07-13 13:15  xiazdong  阅读(1864)  评论(6编辑  收藏  举报