1. switch中增加对String类型的支持。
public void getType(String type){
switch(type){
case "1":
System.out.println("type1");
break;
case "2":
System.out.println("type2");
break;
case "3":
System.out.println("type3");
break;
default:
System.out.println("type error");
}
}
1) case只有一种情况,直接转成if;
2) 如果只有一个case和default,则直接转换为if...else;
3) 有多个case,先将String转换为hashCode,然后对应的进行处理,JavaCode在底层兼容Java7以前版本。
2. 数字字面量的改进
① 增加二进制表示
Java7前支持十进制(123)、八进制(0123)、十六进制(0X12AB)
Java7增加二进制表示(0B11110001、0b11110001)
② 数字中可添加分隔符
Java7中支持在数字量中间增加'_'作为分隔符,更直观,如(12_123_456),下划线只能在数字中间,编译时编译器自动删除数字中的下划线。
3. 异常处理
① Throwable类增加addSuppressed方法和getSuppressed方法,支持原始异常中加入被抑制的异常。
异常抑制:在try和finally中同时抛出异常时,finally中抛出的异常会在异常栈中向上传递,而try中产生的原始异常会消失。
在Java7之前的版本,可以将原始异常保存,在finally中产生异常时抛出原始异常:
public void read(String filename) throws BaseException {
FileInputStream input = null;
IOException readException = null;
try {
input = new FileInputStream(filename);
} catch (IOException ex) {
readException = ex; //保存原始异常
} finally {
if (input != null) {
try {
input.close();
} catch (IOException ex) {
if (readException == null) {
readException = ex;
}
}
}
if (readException != null) {
throw new BaseException(readException);
}
}
}
public void read(String filename) throws IOException {
FileInputStream input = null;
IOException readException = null;
try {
input = new FileInputStream(filename);
} catch (IOException ex) {
readException = ex;
} finally {
if (input != null) {
try {
input.close();
} catch (IOException ex) {
if (readException != null) { //此处的区别
readException.addSuppressed(ex);
}
else {
readException = ex;
}
}
}
if (readException != null) {
throw readException;
}
}
}
public void testSequence() {
try {
Integer.parseInt("Hello");
}
catch (NumberFormatException | RuntimeException e) { //使用'|'分割,多个类型,一个对象e
}
}
public void read(String filename) throws IOException {
try (BufferedReader reader = new BufferedReader(new FileReader(filename))) {
StringBuilder builder = new StringBuilder();
String line = null;
while((line=reader.readLine())!=null){
builder.append(line);
builder.append(String.format("%n"));
}
return builder.toString();
}
}
public void copyFile(String fromPath, String toPath) throws IOException {
try ( InputStream input = new FileInputStream(fromPath);
OutputStream output = new FileOutputStream(toPath) ) {
byte[] buffer = new byte[8192];
int len = -1;
while( (len=input.read(buffer))!=-1 ) {
output.write(buffer, 0, len);
}
}
}
public int sum(int... args) {
int result = 0;
for (int value : args) {
result += value;
}
return result;
}
@SafeVarargs
public static T useVarargs(T... args) {
return args.length > 0 ? args[0] : null;
}
VarargsWarning.useVarargs(new ArrayList());