Conversion between character and int in Java

后端 未结 3 1187
我在风中等你
我在风中等你 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:12

    Actually, converting from int to char is legal, it just requires an explicit cast because it can potentially lose data:

    int i = 88; 
    char c = (char) i;
    

    However, with the literal, the compiler knows whether it will fit into a char without losing data and only complains when you use a literal that is too big to fit into a char:

    char c = 70000; // compiler error
    

提交回复
热议问题