java - 为什么我不能添加两个字节并获得一个 int,而我可以添加两个最终字节获得一个字节?

标签 java int variable-assignment scjp ocpjp

public class Java{
    public static void main(String[] args){
        final byte x = 1;
        final byte y = 2;
        byte z = x + y;//ok
        System.out.println(z);

        byte a = 1;
        byte b = 2;
        byte c = a + b; //Compiler error
        System.out.println(c);
    }
}

如果涉及任何 int 大小或更小的表达式的结果始终是 int,即使两个字节的总和适合一个字节。

为什么当我们添加两个适合一个字节的最终字节时会发生这种情况? 没有编译器错误。

最佳答案

From the JLS 5.2 Assignment Conversion

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 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 byte x = 1;
 final byte y = 2;
 byte z = x + y;//This is constant expression and value is known at compile time

因此,当求和适合字节时,它不会引发编译错误。

如果你这样做了

final byte x = 100;
final byte y = 100;
byte z = x + y;// Compilation error it no longer fits in byte

关于java - 为什么我不能添加两个字节并获得一个 int,而我可以添加两个最终字节获得一个字节?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13100019/

相关文章:

java - 案件被跳过并被送去抓捕?

java - 向串口写入数据,发送错误字符

java - 如果发生什么情况,我怎样才能使之前的整数改变数字?

variable-assignment - 用于线性瓶颈分配 (LBAP) 的代码或伪代码?

java - 在 Spring Boot 1.5 中使应用程序既独立又依赖

java - 使用spring security时如何在velocity宏中获取csrf token

python - 获取整数的后三位数字

c++ - 随机选择 2 个不在范围内的整数?

c - "int *p =0;"和 "int *p; *p=0;"有什么区别

java - 不使用 `return` 将值传递给调用者