简体   繁体   English

此Java println调用中的char转换有什么作用?

[英]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));

  1. 'a' is a char literal; 'a'是一个char文字;
  2. char is an intergral numeric type in Java, just like int ; char是Java中的int数字类型,就像int一样;
  3. + occurring between two numeric values means addition ; 在两个数值之间出现+表示加法 ;
  4. (char) indicates a conversion into a char type; (char)表示转换char类型;
  5. a 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的值a97 ,从而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
  1. 'a' == 97 'a'== 97
  2. 97+4 == 101 97 + 4 == 101
  3. (char)101 == 'e' (char)101 =='e'
  4. System.out.println('e'+""); 的System.out.println( 'E' + “”); // prints 'e' //打印'e'

首先将ascii值添加到值4,然后打印与值101对应的字符。它是'e'。您可以参考ascii表

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM