什么是点型铸造? [英] What is point of type casting?

查看:131
本文介绍了什么是点型铸造?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在此程式码片段中:

c = (char)(c - 'A' + 'a');

为什么我们需要(char) ?这是类型转换正确吗?

Why do we need the (char)? That's type casting right?

假设赋值语句右边的 c 是大写字母。我假设我们在这里进行Unicode加减法。

Assume the c on the right side of the assignment statement is a capital letter. I assume we're doing Unicode addition and subtraction here.

这是我读的Java书中的代码片段:

This is the snippet from the Java book that I'm reading:


当对char进行算术运算时,首先将其转换为代表Unicode系统的int
。从
变量中减去'A',基本上会问大写字母是多大的字母是
的字符在c?添加'a'然后得到相同的int
距离到小写字母字符代码序列中。
需要转换为char,因为char是一种特殊的int类型,
是一个更有限的值范围。通过使用转换,程序员
确认他或她理解
赋值的特殊性质,并期望该值在正确的范围0到
66535中。

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) cast的点?如果我们不使用(char) cast,会有什么不同?

I don't understand the point of the (char) cast? What would be different if we didn't use the (char) cast? What is casting more generally?

推荐答案

char 整数类型,当您执行算术时结果是 int JLS-4.2.2。整数操作部分地说明数值运算符,其导致类型 int 或 long ,并添加添加运算符 + - )。

char is an integral type in Java, and when you perform arithmetic the result is an int (JLS-4.2.2. Integer Operations says, in part, the numerical operators, which result in a value of type int or long and adds that does include the additive operators + and -).

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

这篇关于什么是点型铸造?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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