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

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

问题描述

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

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

所以我有这本书说,char原语需要显式转换短和字节,这一切都有意义,因为数据类型的允许范围不重叠。

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.

有人可以解释为什么会允许这样做吗?

Can some one explain, why this is allowed?

'< 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类型的常量表达式,char或int

这篇关于Java - 为什么char被隐式转换为byte(和short)原语,当它不应该?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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