Java - 为什么 char 不应该被隐式转换为字节(和短)原语? [英] Java - why does char get implicitly cast to byte (and short) primitive, when it shouldn't?

查看:24
本文介绍了Java - 为什么 char 不应该被隐式转换为字节(和短)原语?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Certain functionality of the compiler puzzles me (Oracle JDK 1.7 using Eclipse).

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

So I've got this book that says char primitive needs to be explicitly cast to short and byte and this all makes sense due the data types' allowed ranges don't overlap.

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

In other words below code works (but wouldn't work without the explicit type casts):

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

打印 b 或 s 正确显示数字 38,它是 Unicode 中 (&) 的数字等价物.

Printing b or s correctly displays the number 38, which is the numeric equivalent of (&) in 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

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

Now I would certainly understand the following (which works too):

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

但是这种没有编译器警告的字符到字节(和短的)潜行转换"对我来说似乎不合适.

But this no-compiler-warning char to byte (and short) "sneak conversion" doesn't seem right to me.

谁能解释一下,为什么允许这样做?

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

Could the reason be in the interpretation of the '<char>' itself, so that it doesn't actually ever get to a char primitive state but is handled as a numeric (octal or hexadecimal etc) value?

推荐答案

基本上,赋值转换规范指定

另外,如果表达式是一个常量表达式(§15.28)输入 byte、short、char 或 int:

In addition, if the expression is a constant expression (§15.28) of type byte, short, char, or int:

如果类型为变量是 byte、short 或 char,以及常量的值表达式可以用变量的类型来表示.

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 不应该被隐式转换为字节(和短)原语?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆