Why can I assign an int to a char variable without an explicit cast?
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 to an 开发者_JS百科int
and then for assigning int
to char
, won't we need an explicit cast?
Similarly, I understand what happens when you do ch1 = 65
. But since Java does not allow automatic down type conversion, don't we need explicit cast from int
to char
?
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.
I'm using Eclipse at the moment. There are two things to note:
- The compiler checks for bounds during initialization.
- The compiler calculates the values of constant expressions, such as
3 * (2 + 1)
.
This works:
byte b = 127; // works, range of a byte is [-128, 127]
But this does not:
byte b = 128; // does not work, outside of range
This works:
byte b = 100 + -228; // works, 100 + -228 = -128
But this does not:
byte b = 1;
byte c = b + 1; // does not work, why not?
And this does not, either:
byte b = 1;
byte c = b + (byte) 1; // does not work, why not?
Note that b
is a variable expression. If a variable expression is involved, the result of the operator +
is at least as large as an int. Therefore, you can't assign it to c
. Unlike constant expressions, the compiler does not calculate variable expressions.
The compiler would similarly complain for short
and char
- try it out yourself.
And finally, using final
on a variable effectively turns it into a constant expression, so this would work:
final byte b = 1;
byte c = b + 1; // works
精彩评论