本来整数(以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 }
本来表示一个很长的数字时,会看的眼花缭乱(好比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 只支持: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 }
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(),则: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 }
本来若是在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 }