In java why we can't assign int to char directly??? but vice-versa is true?

前端 未结 4 954
夕颜
夕颜 2020-12-22 02:18
public class CharAndIntTest {

    public static void main(String[] args) {
        char i=\'1\';
        int ii=65;
        i=ii;
    }

}
4条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-22 02:44

    The assignment conversion (JLS, Section 5.2) allows a primitive widening conversion, but not a primitive narrowing conversion:

    Assignment conversion occurs when the value of an expression is assigned (§15.26) to a variable: the type of the expression must be converted to the type of the variable.

    Assignment contexts allow the use of one of the following:

    • an identity conversion (§5.1.1)

    • a widening primitive conversion (§5.1.2)

    • a widening reference conversion (§5.1.5)

    • a boxing conversion (§5.1.7) optionally followed by a widening reference conversion

    • an unboxing conversion (§5.1.8) optionally followed by a widening primitive conversion.

    So you must cast to perform a primitive narrowing conversion, unless

    In addition, if the expression is a constant expression (§15.28) of type byte, short, char, or int:

    • A narrowing primitive conversion may be used if the type of the variable is byte, short, or char, and the value of the constant expression is representable in the type of the variable.

    So assigning a literal will work:

    char a = 65;
    

提交回复
热议问题