Why can not I add two bytes and get an int and I can add two final bytes get a byte?(为什么我不能添加两个字节并获得一个 int,而我可以添加两个最终字节获得一个字节?)
问题描述
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,即使两个字节的总和适合一个字节.
If the result of an expression involving anything int-sized or smaller is always an int even if the sum of two bytes fit in a byte.
为什么当我们添加两个适合一个字节的最终字节时会发生这种情况?没有编译器错误.
推荐答案
来自JLS 5.2 赋值转换
此外,如果表达式是 byte、short、char 或 int 类型的常量表达式(第 15.28 节):- 如果类型为变量是 byte、short 或 char,以及常量的值表达式可以用变量的类型来表示.
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.
简而言之,表达式的值(在编译时是已知的,因为它是一个常量表达式)可以用字节变量的类型来表示.
In short the value of the expression (which is known at compile time, because it is a constant expression) is representable in the type of the variable that is byte.
考虑你的表达方式
final byte x = 1;
final byte y = 2;
byte z = x + y;//This is constant expression and value is known at compile time
因此,当求和适合字节时,它不会引发编译错误.
So as summation fits into byte it does not raise an compilation error.
如果你这样做了
final byte x = 100;
final byte y = 100;
byte z = x + y;// Compilation error it no longer fits in byte
这篇关于为什么我不能添加两个字节并获得一个 int,而我可以添加两个最终字节获得一个字节?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么我不能添加两个字节并获得一个 int,而我可以添加两个最终字节获得一个字节?


- Java包名称中单词分隔符的约定是什么? 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01