Java - 为什么 char 在不应该的情况下隐式转换为字节(和短)原语?

标签 java char type-conversion byte implicit-conversion

编译器的某些功能让我感到困惑(使用 Eclipse 的 Oracle JDK 1.7)。

所以我得到这本书说 char 基元需要显式转换为 short 和 byte,这一切都是有道理的,因为数据类型的允许范围不重叠。

换句话说,下面的代码可以工作(但如果没有显式类型转换就无法工作):

char c = '&';  
byte b = (byte)c;
short s = (short)c;

打印 b 或 s 会正确显示数字 38,这相当于 Unicode 中的 (&)。

这让我想到了我的实际问题。为什么以下方法也有效?

byte bc = '&';
short sc = '&';
System.out.println(bc); // Correctly displays number 38 on the console
System.out.println(sc); // Correctly displays number 38 on the console

现在我肯定会理解以下内容(这也有效):

byte bt = (byte)'&';
System.out.println(bt); // Correctly displays number 38 on the console

但这种无编译器警告字符到字节(和短)的“偷偷转换”对我来说似乎不合适。

谁能解释一下,为什么这是允许的?

原因可能在于对 '<char>' 的解释吗?本身,以便它实际上不会进入 char 原始状态,而是作为数字(八进制或十六进制等)值处理?

最佳答案

基本上,specification of 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.

您的'&' 恰好是“byte、short、char 或int 类型的常量表达式”

关于Java - 为什么 char 在不应该的情况下隐式转换为字节(和短)原语?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17063436/

相关文章:

String 类的 Java 1.6 方法不适用于所有字符

更改函数中的指针字符值

python - 如何将 pandas 数据框日期时间列转换为 int?

string - 使用 map 和 toInt 将字符串转换为 Scala 中的数字集合

c++ - 十六进制字符到 std::string 的 constexpr 转换

java - Hibernate xml 文件问题

java - Json异常类型错误

java - 默认情况下未选中抽屉导航项目

java - Mac OS X Big Sur 上 webstart 的 JDialog 全屏问题

C++ - 如何将 char append 到 char*?