java - java中的隐式缩小规则

标签 java narrowing

byte b = 0xFFFFFFFF; //OK, because integer -1 sits between -128 and 127, FINE!!
char ch = 0xFFFFFFFF; //Not OK, because integer -1 does not sit between 0 and 65535, FINE!!
byte b = 0L; //Compiler says Not OK? But long integer 0 sits between -128 and 127?

我不相信 java 编译器在上面代码的第三行中应用的缩小规则。

请帮助我理解这个缩小规则背后的逻辑。

最佳答案

文字 0L 上的 L 后缀使此文字成为 long 类型(64 位有符号整数)。

根据 Java 语言的规则,没有从 longbyte 的隐式缩小。

参见 Java 语言规范 section 5.2 Assignment Contexts :

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.

注意常量表达式的类型不包括long

关于java - java中的隐式缩小规则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30774042/

相关文章:

java - Spring Boot 实体的自定义自动配置

c++ - 是否可以避免初始化列表中的 static_cast ?

c++ - 为什么 `bool b = 2` 工作正常但 `bool b = {2}` 会产生缩小转换的警告?

search-engine - 必应搜索 API : Narrow by date

java - Android:将网页的HTML读入字符串

java - 因此,我正在使用此应用程序,它没有显示任何错误并已成功安装,但运行后便崩溃了

java - 使用 SSL/PKI 保护 Web 服务

c++ - g++编译器中奇怪的将转换范围缩小为两倍到 float 警告

c++ - 从 "float"到 "int"的缩小转换无效

Graph 的 Java 代码及其需求