Java中的整数算术与char和整数文字 [英] Integer arithmetic in Java with char and integer literal
问题描述
有人可以向我解释为什么以下代码在Java中编译好吗?
Can someone explain to me why the following code compiles OK in Java?
char c = 'a' + 10;
为什么这不等于以下,不能编译?
Why is this not equivalent to the following, which does not compile?
int i = 10;
char c = 'a' + i;
Java语言规范(第3.10.1节)规定整数文字的类型为 long
如果后缀为ASCII字母L或l(ell);否则它的类型为 int
(§4.2.1 )。第4.2.2节引用数值运算符,其结果类型为 int
或 long
。因此,在我的理解中,添加的结果应该是 int
,它不能分配给 char
变量 c
。
The Java Language Specification (section 3.10.1) states "An integer literal is of type long
if it is suffixed with an ASCII letter L or l (ell); otherwise it is of type int
(§4.2.1)." Section 4.2.2 refers to "The numerical operators, which result in a value of type int
or long
." So the result of the addition should, in my understanding, be an int
, which cannot be assigned to the char
variable c
.
然而,它编译得很好(至少在Sun JDK 1.6.0版本17和Eclipse Helios中) )。
However, it compiles fine (at least in Sun JDK 1.6.0 release 17 and in Eclipse Helios).
或许是一个人为的例子,但是它用在我教过的Java入门课程中,现在我发现我真的不懂为什么会有效。
Rather an artificial example perhaps, but it is used in an introductory Java course I have been teaching, and it now occurs to me that I don't really understand why it works.
推荐答案
'a'+ 10
是编译时常量表达式,其值为'k'
,它可以初始化类型 char $ c的变量$ C>。这与能够在[-128,127]中使用文字整数分配
byte
变量相同。在[128,255]范围内的字节
可能更烦人。
'a' + 10
is a compile-time constant expression with the value of 'k'
, which can initialise a variable of type char
. This is the same as being able to assign a byte
variable with a literal integer in [-128, 127]. A byte
in the range of [128, 255] may be more annoying.
这篇关于Java中的整数算术与char和整数文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!