Java – 为什么char会被隐式地转换为字节(和简短)原语,什么时候不应该?

编译器的某些功能让我感到困惑(使用 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,or char,and the value of the constant
expression is representable in the type of the variable.

你的’&’恰好是“byte,char或int类型的常量表达式”.

相关文章

1.Linux实时查看Java接口数据的方法 在Linux系统中实时查看J...
应用场景 C端用户提交工单、工单创建完成之后、会发布一条工...
线程类,设置有一个公共资源 package cn.org.chris.concurre...
Java中的数字(带有0前缀和字符串)
在Java 9中使用JLink的目的是什么?
Java Stream API Filter(过滤器)