我对 Java 中的 byte 和 char 感到困惑。我有以下程序段:
byte b = 65;
char c = 65;
short s = 65;
System.out.println("b:"+b+" c:"+c+ " s:"+s); // outputs b:65 c:A s:65
b、c 和 s 的位表示相同,均为::00000000 01000001 。
我的问题是,如果这些位相同,那么它们的行为有何不同 - b 作为字节,c 作为 char 和 s 作为短?
另一个问题是:char c = 65;
为什么这是一个正确的陈述?尽管我将 int 值分配给 char,但它不会给出错误。
谢谢。
最佳答案
他们的行为有何不同?
请参阅JLS :
The integral types are byte, short, int, and long, whose values are 8-bit, 16-bit, 32-bit and 64-bit signed two's-complement integers, respectively, and char, whose values are 16-bit unsigned integers representing UTF-16 code units.
The values of the integral types are integers in the following ranges:
For byte, from -128 to 127, inclusive
For short, from -32768 to 32767, inclusive
For int, from -2147483648 to 2147483647, inclusive
For long, from -9223372036854775808 to 9223372036854775807, inclusive
For char, from '\u0000' to '\uffff' inclusive, that is, from 0 to 65535
另一个区别是它们的包装类不同:byte
到 Byte
, char
到 Character
和 >短
到短
。
char c = 65;
为什么这是正确的语句?
char, whose values are 16-bit unsigned integers representing UTF-16 code units (§3.1).
关于java - Java 中的 byte、char、int - 位表示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17166393/