Typecasting from int to char and ASCII values

后端 未结 3 469
滥情空心
滥情空心 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:32

    About why char ch22 = (char) a11 works

    From java specification

    A narrowing primitive conversion may lose information about the overall magnitude of a numeric value and may also lose precision and range.

    [...]

    A narrowing conversion of a signed integer to an integral type T simply discards all but the n lowest order bits, where n is the number of bits used to represent type T. In addition to a possible loss of information about the magnitude of the numeric value, this may cause the sign of the resulting value to differ from the sign of the input value.


    About why char c = 65536 doesn't work

    From java specification

    A narrowing primitive conversion followed by a boxing conversion may be used if the type of the variable is:

    • Byte and the value of the constant expression is representable in the type byte.
    • Short and the value of the constant expression is representable in the type short.
    • Character and the value of the constant expression is representable in the type char.

    65536 is not inherently a char value

    For example

    • 1 is at the same time a byte, a short, a char, an int and a long value.
    • 256 is a short, char, int and long value, but not a byte value.
    • 65535 is a char, int and long value, but neither byte nor short value.
    • -1 is a byte, short, int, long value, but not a char value.
    • 65536 is only an int and long value.

    char c = (char)65536; will work

提交回复
热议问题