What is the difference between Short and Character apart from processing?

前端 未结 2 1581
傲寒
傲寒 2021-01-05 08:18

For what I know:

  • \"bytewise\", it looks like they are the same (they are both 2 bytes long);
  • Character, however, has more processing to i
相关标签:
2条回答
  • 2021-01-05 08:48

    They're currently incompatible, and that could never be changed. But to guess why they were originally different -- it's probably a really good idea to have different types for numerical data and letters, even if their contents work exactly the same way, just to avoid getting them mixed up. That would be bad.

    0 讨论(0)
  • 2021-01-05 09:06

    The essential difference is that short is signed, char is unsigned.

    public class CharVsShort {
      public static void main(String[] args) throws Exception {
        short ffShort = (short)0xFFFF;
        char ffChar = (char)0xFFFF;
    
        System.out.println("all-1s-short = " + (int)ffShort);
        System.out.println("all-1s-char  = " + (int)ffChar);
      }
    }
    

    prints

    all-1s-short = -1
    all-1s-char  = 65535
    

    The Java Language Specification section 4.2 states that

    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

    (my bold). It also gives the types' ranges explicitly as

    • byte, from -128 to 127, inclusive
    • short, from -32768 to 32767, inclusive
    • int, from -2147483648 to 2147483647, inclusive
    • long, from -9223372036854775808 to 9223372036854775807, inclusive
    • char, from '\u0000' to '\uffff' inclusive, that is, from 0 to 65535
    0 讨论(0)
提交回复
热议问题