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
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.