In data Type hierarchy char is before int, therefore int needs to be type cast into char for its conversation into char. But when I ran above snippet it threw no error and successfully output was A. Can I know the reason?
public class ecd {
public static void main(String[] args) {
char a; a = 65;
System.out.print(a);
}
}
This is allowed because of the way Assignment Conversions work in Java.
Assignment conversion occurs when the value of an expression is assigned to a variable: the type of the expression must be converted to the type of the variable.
If the expression is a constant expression 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.
In your code, the expression is a constant int value and the variable is of type char. The int value can be represented in char type using a ASCII value.
This is the reason Java compiler allows this conversion without the need of explicit casting.
If instead of constant int value, you try to assign a int variable to a char variable without casting, you'll get a compilation error.
For more details, refer this.