java - Java 中的缩小类型转换到底是什么?

标签 java narrowing

<分区>

根据我对 Java 的了解,如果 source 位于字节范围内的任何常量中,则在缩小类型转换时允许以下内容:

byte b=10; // allowed because 10 is in range of byte and 10 is a constant

但是当我输入这个时:

byte b=10l; // this is not allowed although 10 is in range of byte and is a constant 

为什么会这样? 您能否说出这些缩小转换在 Java 中发生的确切规则。

最佳答案

http://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-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.

您有一个 long 类型的常量表达式,在这种情况下不能应用缩小原始转换。

所以你可以这样做:

  • 字节 b = 10
  • byte b = (int) 10
  • char b = (short) 10
  • byte b = (char) 10L
  • 短 b = (int) 10L

但是你不能这样做:

  • 字节 b = 10L
  • byte b = (long) 10

关于java - Java 中的缩小类型转换到底是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23949132/

相关文章:

c++ - 在初始化列表的上下文中缩小的奇怪行为

c++ - G++ 警告 : narrowing conversion of

c++ - 将 '65280' 从 'int' 缩小到 { } 内的 'short int'

java - 如何在 Swing 中实现分层 "selection tree"? (或 : is there an existing implementation? )

Java判断字符串是否以Map中的Key开头

java - 在java中查找和替换重复项

java - Java 中的类型安全枚举

java - GridBagLayout 似乎锚定在底部,并扩展标签

C++:使用大括号防止赋值时变窄

java - 在 Java 中强制返回类型缩小?