Conversion between character and int in Java

后端 未结 3 1194
我在风中等你
我在风中等你 2020-11-30 10:52

You cannot convert from int to char, so this would be illegal int i = 88; char c = i;,

However this is allowed char c = 88;.

Isn\'t

3条回答
  •  臣服心动
    2020-11-30 11:22

    Its because the literals for integer or smaller than int as byte ,short and char is int. Understand the following in this way.

    code:

      byte a = 10;//compile fine
      byte b= 11;//compile fine
      byte c = a+b;//compiler error[says that result of **a+b** is **int**]
    

    the same happens for any mathematical operations as of 'Divide', 'multiply', and other arithmetic operation. so cast the result to get the literal in desired data type

    byte c = (byte)(a+b);
    

    So that the same reason why the value int need to have primitive cast to change the value in char. Hope this make some sense.

提交回复
热议问题