Why do I need to explicitly cast char primitives on byte and short?

前端 未结 2 1343
心在旅途
心在旅途 2020-12-12 01:51

Concerning primitives: When I cast from smaller to bigger types, the casts are implicit, when I cast from bigger to smaller types, I need to explicitly cast the primitives,

相关标签:
2条回答
  • 2020-12-12 02:19

    char is Java's only unsigned type, therefore its value range does not fully contain any other Java type's value range.

    You must use an explicit cast operator for any conversion where the target type's range doesn't fully cover the source type's range.

    0 讨论(0)
  • 2020-12-12 02:25

    I've taken this from the language specification:

    "First, the byte is converted to an int via widening primitive conversion (§5.1.2), and then the resulting int is converted to a char by narrowing primitive conversion (§5.1.3)."

    0 讨论(0)
提交回复
热议问题