Why can I assign an int to a char variable without an explicit cast?

后端 未结 2 1633
挽巷
挽巷 2021-01-18 06:17

I wanted to know why this snippet works.

char ch1;
ch1 = \'a\' + 1;
System.out.println(ch1);

In line 2, isn\'t the right hand side promoted

2条回答
  •  终归单人心
    2021-01-18 06:51

    Because the Java Language Specification says:

    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 you're right in that the expression is promoted to int, but because it's a constant expression, the cast is not necessary. If it involved a variable (or its value did not fit into a char), it would be different.

    For this kind of question it's best to look at the language specification right away, as it's the authoritative source and quite readable for a specification.

提交回复
热议问题