Java:Java7新语法:修订间差异

来自WHY42
imported>Soleverlee
imported>Soleverlee
→‎xx
 
(未显示同一用户的6个中间版本)
第15行: 第15行:
</source>
</source>


=数值字面量=
=数值字面量改进=
可以试用0b...表示二进制数值;可以在数值间插入任意多的下划线分隔,利于(bu li)阅读。
<source lang="java">
double x = 1000_8000.01;
double y = 999_988_________________________________________________________________98.09;
 
int b = 0b100100100;
int c = 0b111000111;
</source>
 
=异常捕获=
可以在一行申明多个异常捕获。
<source lang="java">
catch(ExteptionA | ExceptionB){
...
}
</source>
 
=try-with-resource=
不用再繁杂的写try-catch-finally啦!这一个语法能保证资源的释放。当然不是所有的类型都可以这样写,看来是需要实现了AutoCloseable接口才行。
<source lang="java">
//try(File f = new File("c:/xx.txt")){
//}
//ERROR: Error:(33, 18) java: 不兼容的类型: try-with-resources 不适用于变量类型
//      (java.io.File无法转换为java.lang.AutoCloseable)
 
try(OutputStream s = new BufferedOutputStream(new FileOutputStream(new File("t.txt")))){
 
}
</source>
这种新特性还能同时对多个资源进行管理。
<source lang="java">
try(
InputStream i = new FileInputStream("c:/1.txt");
OutputStream o = new FileOutputStream("c:/2.ext")
){
 
}
</source>
 


[[Category:Programe]]
[[Category:Programe]]

2016年6月13日 (一) 02:39的最新版本

switch中使用字符串

JDK7中允许在switch中使用字符串。但实际在内部实现时,还是通过转换为数字实现的。

public int switchFunc(String name){
	switch(name){
		case "Riguz":
			return 1;
		case ".Com":
			return -1;
		default:
			break;
	}
	return 0;
}

数值字面量改进

可以试用0b...表示二进制数值;可以在数值间插入任意多的下划线分隔,利于(bu li)阅读。

double x = 1000_8000.01;
double y = 999_988_________________________________________________________________98.09;

int b = 0b100100100;
int c = 0b111000111;

异常捕获

可以在一行申明多个异常捕获。

catch(ExteptionA | ExceptionB){
...
}

try-with-resource

不用再繁杂的写try-catch-finally啦!这一个语法能保证资源的释放。当然不是所有的类型都可以这样写,看来是需要实现了AutoCloseable接口才行。

//try(File f = new File("c:/xx.txt")){
//}
//ERROR: Error:(33, 18) java: 不兼容的类型: try-with-resources 不适用于变量类型
//      (java.io.File无法转换为java.lang.AutoCloseable)

try(OutputStream s = new BufferedOutputStream(new FileOutputStream(new File("t.txt")))){

}

这种新特性还能同时对多个资源进行管理。

try(
		InputStream i = new FileInputStream("c:/1.txt");
		OutputStream o = new FileOutputStream("c:/2.ext")
		){

}