Typecasting from int to char and ASCII values

后端 未结 3 458
滥情空心
滥情空心 2020-12-22 14:04
int a1 = 65535;

char ch2 = (char) a1;

System.out.println(\"ASCII value corresponding to 65535 after being typecasted : \"+ch2);// prints?
char ch3 = 65535;
System.         


        
3条回答
  •  天涯浪人
    2020-12-22 14:22

    Java's char type holds a Unicode/UTF-16 code unit, one or two of which encode a codepoint. Not all 16-bit positive integers are valid code units. And, since you want to deal with char instead of String, you'll want to restrict the values to codepoints encoded with only one code unit.

    65535 is not a valid UTF-16 code unit nor a valid Unicode codepoint.

    As to your question, why you don't get an exception, I can only compare with other integer-like operations where you don't get an exception for overflows and similar exceptional outcomes. Languages vary in their design compromises.

    I'll submit, if you are doing the right thing—the right way—with char or Character or String, you won't run into problems like this. Forget about "ASCII still ranges from 0 to 127 as always, and the extended 8-bit character set, ISO-Latin-1." Java uses Unicode; Embrace it.

提交回复
热议问题