java - Java 中的原始类型转换和赋值

标签 java

我明白为什么以下是错误的:

byte a = 3; 
byte b = 8; 
byte c = a + b;  // compile error

它不会编译。表达式总是产生 int。所以我们应该进行显式转换:

byte c = (byte) (a + b);   // valid code

但是我不明白为什么以下是正确的:

byte d = 3 + 8;   // it's valid! why?

因为文字整数(例如 3 或 8)总是隐含的 int。而 int-or-smaller 表达式也总是会产生一个 int。谁能解释这里发生了什么?

我唯一能猜到的是编译器将此表达式等同于以下内容:

byte d = 11;

并且不认为这是一个表达式。

最佳答案

less†3 + 8 在编译时是否被评估为 11 以及 更多 与编译器被明确允许在某些情况下将 ints 隐式缩小到 bytes 的事实有关。特别是,语言规范明确允许在编译时将 int 类型的常量表达式隐式缩小转换为 byte,这些表达式可以适合 byte .

JLS here is section §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 type of the variable is byte, short, or char, and the value of the constant expression is representable in the type of the variable.

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 a = 3; 
byte b = 8; 

允许这些的原因是规范的上述部分。也就是说,允许编译器将文字 3 隐式缩小转换为 byte。这不是因为编译器在编译时将常量表达式 3 计算为其值 3

关于java - Java 中的原始类型转换和赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17110918/

相关文章:

java - GWT 平台代理

java - 为什么这个简单的java代码不能编译?

java - 使用 Java 在 PostgreSQL 中存储时间的最推荐方法是什么?

java - 根据第一个 Activity 中的微调器更改第二个 Activity 中的逻辑

java - Java中按对象类型对对象列表进行排序

java - Java 中的多线程任务仅在 onClick Button 时工作一次

java - 是否可以在不进行修改的情况下从使用 Jython 的 Java 程序中使用 python 模块?

java - 不包括空格的正则表达式程序更改

java - 遍历java中一条线/路径上的每个点

java - 需要对方法调用进行解释