有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java中的强制转换和转换

升级意味着将较小的类型文字升级或转换为较高的类型。此提升用于计算表达式。现在我对此有点怀疑。当我键入此语句时

byte var1 = 56 + 10;

答案是66。这怎么可能呢? 根据提升规则,每个字节、short和char都被提升为int。因此,56和10将被提升为int,因此答案66将是int。这66将存储在字节类型的变量中。然而,要存储从int到byte的内容,需要进行转换。但是这段代码在没有强制转换的情况下可以完美地工作


共 (2) 个答案

  1. # 1 楼答案

    这没关系,因为你给的是常量值。见compile-time narrowing of constants

    The compile-time narrowing of constants means that code such as:

    byte theAnswer = 42;

    is allowed. Without the narrowing, the fact that the integer literal 42 has type int would mean that a cast to byte would be required:

    byte theAnswer = (byte) 42; // cast is permitted but not required

  2. # 2 楼答案

    与许多情况一样,在Java Language Specification § 5.2中可以找到这一点:

    In addition, if the expression is a constant expression (§15.28) of type byte, short, char, or int:

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

    这意味着编译器首先扩展到int,然后缩小到目标类型,因为66确实可以在目标类型(即字节)中表示


    请注意,这仅适用于常量表达式。例如,以下代码产生编译时错误:

    static int get() {
        return 10;
    }
    
    public static final main(String[] args) {
        byte var1 = 56 + get();
    }