加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-15 02:52:33 所属栏目:Java 来源:网络整理
导读:编译器的某些功能让我感到困惑(使用 Eclipse的Oracle JDK 1.7). 所以我有这本书说char原语需要明确地转换为short和byte,这一切都有意义,因为数据类型的允许范围不重叠. 换句话说,下面的代码可以工作(但如果没有显式类型转换,则无法工作): char c = ''; byte
编译器的某些功能让我感到困惑(使用 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类型的常量表达式”.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读