In what encoding is a Java char stored in?

后端 未结 3 1342
忘掉有多难
忘掉有多难 2020-12-05 15:40

Is the Java char type guaranteed to be stored in any particular encoding?

Edit: I phrased this question incorrectly. What I meant to ask is are char literals

3条回答
  •  萌比男神i
    2020-12-05 16:16

    "Stored" where? All Strings in Java are represented in UTF-16. When written to a file, sent across a network, or whatever else, it's sent using whatever character encoding you specify.

    Edit: Specifically for the char type, see the Character docs. Specifically: "The char data type ... are based on the original Unicode specification, which defined characters as fixed-width 16-bit entities." Therefore, casting char to int will always give you a UTF-16 value if the char actually contains a character from that charset. If you just poked some random value into the char, it obviously won't necessarily be a valid UTF-16 character, and likewise if you read the character in using a bad encoding. The docs go on to discuss how the supplementary UTF-16 characters can only be represented by an int, since char doesn't have enough space to hold them, and if you're operating at this level, it might be important to get familiar with those semantics.

提交回复
热议问题