在这段代码中:
c = (char)(c - 'A' + 'a');
为什么我们需要(char)?那是铸造权吗?
假设赋值语句右侧的c是大写字母.我假设我们在这里做Unicode加法和减法.
这是我正在阅读的Java书籍的片段:
When arithmetic is done on a char,it is first converted to the int
that represents it in the Unicode system. Subtracting ’A’ from a
variable c essentially asks “How far into the upper-case letters is
the character in c?” Adding ’a’ then yields the int that is the same
distance into the sequence of lower-case alphabetic character code.
The cast to char is needed because char is a special kind of int with
a more limited range of values. By using the cast,the programmer
acknowledges that he or she understands the special nature of the
assignment and expects the value to be in the correct range,0 through
66535.
我不明白(char)的点?如果我们没有使用(char)演员,会有什么不同?什么是更一般的铸造?
解决方法
char是Java中的一个
@L_403_0@,当您执行算术时,结果是一个int(
JLS-4.2.2. Integer Operations表示,部分是数值运算符,它导致int或long类型的值,并且包括加法运算符和 – ).
char c = 'A'; System.out.printf("'%c' = %d%n",c,(int) c); int d = (c - 'A' + 'a'); // c - 65 + 97 System.out.printf("'%c' = %d%n",(char) d,d);
我得到了
'A' = 65 'a' = 97