java - Java 中的 byte、char、int - 位表示

标签 java char byte

我对 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:

  1. For byte, from -128 to 127, inclusive

  2. For short, from -32768 to 32767, inclusive

  3. For int, from -2147483648 to 2147483647, inclusive

  4. For long, from -9223372036854775808 to 9223372036854775807, inclusive

  5. For char, from '\u0000' to '\uffff' inclusive, that is, from 0 to 65535

另一个区别是它们的包装类不同:byteBytecharCharacter >短

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/

相关文章:

java - JMockit mock 没有被破坏

SQL ORDER 字符数字

java - (var) 无法解析为类型

c++ - 如何获取以字符串和其他用户定义类型作为数字的给定结构的大小(以字节为单位)?

java - 启动tomcat服务器报错

java - 使用 Apache POI 读取 Excel 工作表的列

c - %u 需要 unsigned int 参数,但参数类型为 long int (4294967295)

c# - 显示来自 byte[ ] 的图像

java - TestNG + Mockito,如何测试抛出的异常和模拟调用

c++ - 如何在不越过缓冲区的情况下将字符串复制到 C++ 中的 char 数组中