[英]What does char casting in this Java println call do?
I'm new to programming in java and I do not understand a println statement. 我是Java编程的新手,但我不了解println语句。 I can run it but cannot understand what it does.
我可以运行它,但不了解它的作用。 Can anyone explain what this does?
谁能解释这是什么?
System.out.println((char) ('a' + 4));
'a'
is a char
literal; 'a'
是一个char
文字; char
is an intergral numeric type in Java, just like int
; char
是Java中的int
数字类型,就像int
一样; +
occurring between two numeric values means addition ; +
表示加法 ; (char)
indicates a conversion into a char
type; (char)
表示转换为char
类型; char
, when printed, renders as the Unicode codepoint it represents. char
表示为其表示的Unicode代码点。 That simply prints out the letter e
. 那只是打印出字母
e
。 @wrongAnswer has referenced the ASCII character codes, which is a numbering system that assigns unique IDs to characters. @wrongAnswer已引用ASCII字符代码,这是一种为字符分配唯一ID的编号系统。 Take a look at this one for example: http://www.asciitable.com/ .
看看这个例子: http : //www.asciitable.com/ 。
If you take a look at the way the lower case letters are arranged in the table, you'll see that the letter a
is at 97, b
is at 98, c
is at 99 and so on. 如果查看表中小写字母的排列方式,您会看到字母
a
在97处, b
在98处, c
在99处,依此类推。 What the above code is doing is that we are finding what the ASCII code of a
is, then adding by 4, then casting back to char
. 上面的代码正在做的是找到
a
的ASCII码,然后加4,然后转换回char
。 Therefore, what this is actually doing is taking 97
then adding with 4
, producing 101
. 因此,这实际上是在做
97
然后加4
,得到101
。 If you consult the table, 101
is actually e
, and so the output is e
after casting 101
with char
. 如果查询该表,则
101
实际上是e
,因此在用char
强制转换101
之后的输出是e
。
the ascii
value of a
is 97
so 97+4=101
101
which is ascii
value of alphabets e
. 所述
ascii
的值a
是97
,从而97+4=101
101
这是ascii
字母的值e
。
System.out.println((char) ('a' + 4));
so the above sop will print e
. 因此上述sop将打印
e
。
Lets break this down into discrete statements: 让我们将其分解为离散的语句:
char a = 'a'; // the character a
int aPlusFour = a + 4; //characters are really an integer value for the ASCII code, so we can add four
char aPlusFourChar = ((char) aPlusfour); //cast our integer back to a char
System.out.println(aPlusFourChar); //this should print the character e
首先将ascii值添加到值4,然后打印与值101对应的字符。它是'e'。您可以参考ascii表
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.