Java7相对于Java6的新变化

1. 允许switch语句中使用String表达式

Java7之前,switch的条件表达式类型只能是枚举类型,或者byte、char、short、int类型已或者Byte、Character、Short和Integer。

Java7之后允许条件表达语句是String类型了。

2. 允许数值以下划线分割

Java7之后下面的代码是合法的:

long a = 10_000_000L;
int b = 0b1100_1000_0011_0000;

大大增加了代码的可读性。 

3. 允许数值以二进制表示

Java7之前数值只支持十进制(默认)、八进制(前缀为“0”)和十六进制(前缀为“0x”或“0X”)。

Java7之后允许使用前缀为“0b”或者“0B”表示二进制。

        //十进制转换为二进制
        System.out.println(Integer.toBinaryString(10));

4. 异常处理增强

 Java7之前的多异常处理:

        try {
            FileInputStream fs = new FileInputStream("");
            OutputStream os = new FileOutputStream("");
            int b = 0 / 0;
            int a = Integer.parseInt( "a", b);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }

Java7之后的多异常处理:

        try {
            FileInputStream fs = new FileInputStream("");
            OutputStream os = new FileOutputStream("");
            int b = 0 / 0;
            int a = Integer.parseInt( "a", b);
        } catch (FileNotFoundException | NumberFormatException e) {
            e.printStackTrace();
        }

 5. try-with-resources

 Java7之前的资源管理:

        FileInputStream fs = null;
        OutputStream os = null;
        try {
            fs = new FileInputStream("");
            os = new FileOutputStream("");
        } catch (FileNotFoundException | NumberFormatException e) {
            e.printStackTrace();
        } finally {
            try {
                fs.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

Java7之后的资源管理:

        try (FileInputStream fs = new FileInputStream("");
              FileOutputStream os = new FileOutputStream("")) {
            fs.read();
            os.write("".getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }

        try-with-resources这种声明方式指定了一个或多个资源,而且这些资源需要在程序结束的时候进行关闭。这种方式可以确保每个指定的资源都可以在声明结束的时候进行关闭(就是在try(){}结束的时候)。但是前提是这些资源必须实现接口java.lang.AutoCloseable(其中包括实现了java.io.Closeable接口的所有对象),原因是java.io.Closeable接口继承了java.lang.AutoCloseable接口。

在Java se 7中的try-with-resource机制中异常的抛出顺序与Java se 7以前的版本有一点不一样,是先声明的资源后关闭。

6. 简化泛型定义、简化变长参数的方法调用等

看下面的实例代码相信大家很快就认识了。

Map<String, Set<Long>> mapJava6  = new HashMap<String, Set<Long>>();
Map<String, Set<Long>> mapJava7  = new HashMap<>();

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值