Java – why can I assign a value to a char variable without explicit conversion?

I wonder why this clip works

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

In line 2, instead of promoting the right side to int and assigning int to char, do we need an explicit conversion?

Again, I understand what happens when you execute ch1 = 65 But since Java doesn't allow automatic downward type conversion, don't we need an explicit conversion from int to char?

Solution

Because the Java language specification says:

So you are right because the expression is promoted to int, but because it is a constant expression, there is no need to cast If it involves a variable (or its value is not suitable for char), it is different

For such problems, it is best to check the language specification immediately, because it is a source of authority and is very easy to read for the specification

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>