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

来自WHY42
imported>Soleverlee
→‎xx
imported>Soleverlee
第34行: 第34行:


=try-with-resource=
=try-with-resource=
不用再繁杂的写try-catch-finally啦!这一个语法能保证资源的释放。当然不是所有的类型都可以这样写,看来是需要实现了AutoCloseable接口才行。
<source lang="java">
<source lang="java">
不用再繁杂的写try-catch-finally啦!这一个语法能保证资源的释放。当然不是所有的类型都可以这样写,看来是需要实现了AutoCloseable接口才行。
//try(File f = new File("c:/xx.txt")){
//try(File f = new File("c:/xx.txt")){
//}
//}
第45行: 第45行:
}
}
</source>
</source>
=xx=
=xx=
[[Category:Programe]]
[[Category:Programe]]

2016年6月13日 (一) 02:32的版本

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")))){

}

xx