Java 7 语法新特性

1、二进制数字表达方式

 本来整数(以60为例)可以用十进制(60)、八进制(074)、十六进制(0x3c)表示,惟独不能用二进制表示(111100),Java 7 弥补了这点。java

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 }

2、使用下划线对数字进行分隔表达

本来表示一个很长的数字时,会看的眼花缭乱(好比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 }

3、switch 语句支持字符串变量

本来 Switch 只支持:int、byte、char、short,如今也支持 String 了。spa

 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 }

4、泛型的“菱形”语法

本来建立一个带泛型的对象(好比HashMap)时:
  • Map<String,String> map = new HashMap<String,String>();
不少人就会抱怨:“为何前面声明了,后面还要声明!”。Java 7 解决了这点,声明方式以下:
  • Map<String,String> map = new HashMap<>();

5、自动关闭资源的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 }

6、多异常捕捉

若是在try语句块中可能会抛出 IOException 、NumberFormatException 异常,由于他们是检验异常,所以必须捕捉或抛出。若是咱们捕捉他且处理这两个异常的方法都是e.printStackTrace(),则:code

 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中同时声明多个异常,方法以下:orm

1 try
2 {
3 }
4 catch(IOException | NumberFormatException  e)
5 {
6     e.printStackTrace();    
7 }

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 }
相关文章
相关标签/搜索