So I understand that you can have an implicit cast of int to char and vice versa in most cases and only need to explicitly cast when the int value is greater than a value of FFFF but there are still certain places I'm confused on, in relation to when exactly you must explicitly cast an int to a char and when you can do an implicit cast.
For instance, The following block of code gives a compile-time error of "Type mismatch: Cannot convert from int to char".
public static void main (String[] args)
{
char[] c = {'a','b'};
for (int i=0;i<c.length;i++)
{
c[i] = c[i] + 2;
System.out.println(c[i]);
}
}
The only way to fix it is to explicitly cast it to char:
c[i] = (char) (c[i] + 2);
However, this other strategy, although being logically equivalent doesn't give a compile time error, how come?
c[i] +=2;
Another confusing scenario I have is when you initialize an integer and set the char equivalent to that integer value, you have to cast it explicitly.
int x = 5;
char c = (char) x;
However, of course, the following implicit casting would work just fine.
char c = 5;
Can someone explain to me why these errors and non-errors occur, and in which other general scenarios are explicit casts from int to char are needed and why?