简体   繁体   English

为什么字符数组在Java中接受整数值?

[英]Why a character Array accepts integer values in Java?

Of course I'm a beginner for Java, previously I learned C. Please take a look on the following code segments. 当然,我是Java的初学者,之前我学习过C。请查看以下代码段。

char Character;
int Number = 27;
Character = Number;
System.out.println(Character);

The above code cannot be compiled as an error stated as “Loss of Information” 上面的代码无法编译为错误,提示为“信息丢失”

Whereas the following code... 而以下代码...

char Character = ‘F’;
int Number;
Number = Character;
System.out.println(Number);`

The above code can be compiled but the output is “70”... not as “F” 上面的代码可以编译,但是输出为“ 70” ...而不是“ F”

Also take a look on the following code... 还请看下面的代码...

char [] arrayCh = new char [3];
arrayCh [0] = 27;
System.out.println(arrayCh[0]);

The above code can be compiled however it also gives an unfamiliar symbol... 上面的代码可以编译,但是它也给出了一个陌生的符号...

I know the issues regarding the ASCII Values and the memory taking as 'char' takes 16 Bits, 'int' takes 32 Bits. 我知道有关ASCII值和内存的问题,因为“ char”占用16位,“ int”占用32位。 Therefore an integer value couldn't be assigned in to a character variable whereas a character value can be assigned in to an integer variable as "ASCII" value. 因此,不能将整数值分配给字符变量,而可以将字符值作为“ ASCII”值分配给整数变量。

My question is... why a 'char' array accepts 'int' values..? 我的问题是...为什么'char'数组接受'int'值..? Could anyone explain? 谁能解释?

A char is a 2-bytes long, unsigned integer. 字符是2字节长的无符号整数。 27 is an integer literal that is in the range of a char, so the compiler accepts to let you assign it to a char. 27是在char范围内的整数文字,因此编译器接受让您将其分配给char。

'F' is a character literal that represents the character F, which has the decimal value 70 in the unicode standard. 'F'是代表字符F的字符文字,在Unicode标准中其十进制值为70。 So, assigning 'F' to an integer is the same thing as assigning 70. 因此,将'F'分配给整数与分配70相同。

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

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