在Java中使用final关键字将类型从整数转换为字节 [英] Type cast issue from int to byte using final keyword in java

查看:39
本文介绍了在Java中使用final关键字将类型从整数转换为字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public static void main(String[] args) {

    final int a =15;
    byte b = a;
    System.out.println(a);
    System.out.println(b);
}

在上面的代码中,当我从int转换为byte时,它没有给出编译时错误,但是当我从long转换为int时,却给出了编译时错误,为什么?

In above code when I am converting from int to byte it is not giving compile time error but when my conversion is from long to int it is giving compile time error, WHY?

public static void main(String[] args) {

    final long a =15;
    int b = a; 
    System.out.println(a);
    System.out.println(b);
}

推荐答案

来自

此外,如果表达式是 byte short char int :

  • A narrowing primitive conversion may be used if the type of the variable is byte, short, or char, and the value of the constant expression is representable in the type of the variable.

当您声明并初始化 final a 时,这是一个编译时常量表达式,编译器可以确定值 15 可以安全地放入一个 byte .JLS根本不允许不加解释地从 long 进行隐式变窄转换,并且该规则至少可以追溯到Java 2(我可以在任何地方找到的最早的JLS).

When you're declaring and initializing your final a , that's a compile-time constant expression, and the compiler can determine that the value 15 will safely fit in a byte. The JLS simply does not permit implicit narrowing conversions from long, without explanation, and this rule goes back to at least Java 2 (the earliest JLS I could find anywhere).

我推测,其基本原理可能源于Java字节码是为32位字长定义的,并且对 long 的操作在逻辑上更加复杂且昂贵.

I would speculate that that rationale may stem from the fact that the Java bytecode is defined for a 32-bit word size and that operations on a long are logically more complicated and expensive.

这篇关于在Java中使用final关键字将类型从整数转换为字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆