【Java新特性JDK7】

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/cmm0401/article/details/83036866

【Java新特性JDK7】

二进制字面量。数字字面量可以出现下划线。switch 语句可以用字符串。泛型简化。异常的多个catch合并。try-with-resources 语句。

一、二进制字面量

1、Java7中, 整数类型(byte, short, int以及long) 也可以使用二进制数形式来表示。要指定一个二进制字面量,可以给二进制数字添加前缀 0b 或者 0B
2、分析:Binary: Base 2, whose digits consists of the numbers 0 and 1 (you can create binary literals in Java SE 7 and later)
二进制:基为2的数字,由数字0和1组成(你可以在java SE 7及更新的版本中创建二进制常量)。
具体请参考官网的解释:http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

//代码测试:
public class Demo{
    public static void main(String[] args){
        int i=0b1110;         //0b开头
        System.out.println(i);//输出14
        i=0B11111111;         //0B开头
        System.out.println(i);//输出255
        //int i=1110B; 不能以B和b结尾。报错。
    }
}

二、数字字面量可以出现下划线

1、在Java中,可以在数字字面量中的两位数字之间使用下划线。例如,一个int字面量:2014可以写成2_014,20_14,201_4。

并且允许在八进制,十六进制和二进制格式中使用下划线。Java在数字字面量字中只允许在数字之间使用下划线。

int下划线大数字使得它们更容易阅读。

2、注意事项:下划线不能

  • 不能出现在进制标识和数值之间
  • 不能出现在数值开头和结尾
  • 不能出现在小数点旁边
//int下划线大数字使得它们更容易阅读。
//以下示例显示数字字面量中下划线的有效用法:
int x1  = 2_014;     // Underscore in  deciaml format
int x2  = 2___014;   // Multiple consecutive underscores 
int x3  = 02_014;    // Underscore in  octal literal
int x4  = 0b0111_1011_0001;  // Underscore in binary literal
int x5  = 0x7_B_1;           // Underscores in hexadecimal literal 
byte b1 = 1_2_7;             // Underscores in decimal format 
double d1 = 2_014.01_11;     // Underscores in double literal

三、switch语句可使用字符串

1、在Java7之前,switch语句中的条件表达式的类型只能是与整数类型相兼容的类型,包括基本类型 byte、short、char、int,与这些基本类型对应的封装类 Byte、Short、Character和 Integer,还有枚举类型Enum。

2、这样的限制降低了语言的灵活性,使开发人员在需要根据其他类型的表达式来进行条件选择时,不得不增加额外的代码来绕过这个限制。为此,Java7放宽了这个限制,额外增加了一种可以在switch语句中使用的表达式类型,那就是很常见的字符串,即String 类型
3、代码演示

public class TestSwitch {
	public static void main(String[] args) {
		test("a");
	}
	public static void test(String type) {
		switch (type) {
		case "a":
			System.out.println("aa");
			break;
		case "b":
			System.out.println("bb");
 
			break;
		}
	}
}

四、泛型简化

// 泛型简化前
ArrayList<String> array = new ArrayList<String>();
// 泛型简化后
ArrayList<String> array = new ArrayList<>();

学习泛型:https://www.cnblogs.com/lwbqqyumidi/p/3837629.html

五、异常的多个catch语句可以合并

1、在Java 7中,catch代码块得到了升级,用以在单个catch块中处理多个异常。如果你要捕获多个异常并且它们包含相似的代码,使用这一特性将会减少代码重复度。
2、下面用一个例子来理解。

Java7之前的版本:

    try{
        ...
    } catch (IOException ex) {
        logger.error(ex);
         throw new MyException(ex.getMessage());
     } catch (SQLException ex) {
         logger.error(ex);
         throw new MyException(ex.getMessage());
     } catch (Exception ex) {
         logger.error(ex);
         throw new MyException(ex.getMessage());
    }

在Java7中,我们可以用一个catch块捕获所有这些异常:

    try{
        ...
    } catch(IOException | SQLException | Exception ex){
     logger.error(ex);
     throw new MyException(ex.getMessage());
    }

3、如果用一个catch块处理多个异常,可以用管道符(|)将它们分开,在这种情况下异常参数变量(ex)是定义为final的,所以不能被修改。这一特性将生成更少的字节码并减少代码冗余。
4、另一个升级是编译器对重新抛出异常(rethrown exceptions)的处理。这一特性允许在一个方法声明的throws从句中指定更多特定的异常类型。
让我们来看看一个小例子:

package com.journaldev.util;
public class Java7MultipleExceptions {
    public static void main(String[] args) {
        try{
            rethrow("abc");
        }catch(FirstException | SecondException | ThirdException e){
            //以下赋值将会在编译期抛出异常,因为e是final型的
            //e = new Exception();
            System.out.println(e.getMessage());
        }
    }
    static void rethrow(String s) throws FirstException, SecondException,ThirdException {
        try {
            if (s.equals("First"))
                throw new FirstException("First");
            else if (s.equals("Second"))
                throw new SecondException("Second");
            else
                throw new ThirdException("Third");
        } catch (Exception e) {
            //下面的赋值没有启用重新抛出异常的类型检查功能,这是Java 7的新特性
            // e=new ThirdException();
            throw e;
        }
    }
    static class FirstException extends Exception {
        public FirstException(String msg) {
            super(msg);
        }
    }
    static class SecondException extends Exception {
        public SecondException(String msg) {
            super(msg);
        }
    }
    static class ThirdException extends Exception {
        public ThirdException(String msg) {
            super(msg);
        }
    }
}

分析:如你所见在rethrow方法中,catch块捕获的异常并没有出现在throws从句中。Java 编译器会分析完整的try代码块以检查从catch块中什么类型的异常被抛出和重新抛出。需要注意:一旦改变了catch块的参数,编译器的分析将不会被启用。
原文链接: Journaldev 翻译: ImportNew.com - 吴际
译文链接: http://www.importnew.com/7015.html
[ 转载请保留原文出处、译者和译文链接。]

六、try-witch-resource语句

1、格式:

try(必须是java.lang.AutoCloseable的子类对象){…}

2、好处:

  • 资源自动释放,不需要close()
  • 把需要关闭资源的部分都定义在这里就ok
  • 主要是流体系的对象是这个接口的子类(JDK7API)
private static void method() {
// try-with-resources 语句
// try(必须是java.lang.AutoCloseable的子类对象){…}
try {
	FileReader fr = new FileReader("a.txt");
	FileWriter fw = new FileWriter("b.txt");
	int ch = 0;
	while ((ch = fr.read()) != -1) {
		fw.write(ch);
	}
	fw.close();
	fr.close();
} catch (IOException e) {
	e.printStackTrace();
}
// 改进版的代码
try (FileReader fr = new FileReader("a.txt");
		FileWriter fw = new FileWriter("b.txt");) {
	int ch = 0;
	while ((ch = fr.read()) != -1) {
		fw.write(ch);
	}
} catch (IOException e) {
	e.printStackTrace();
}

猜你喜欢

转载自blog.csdn.net/cmm0401/article/details/83036866