0

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?

Simar Chhabra
  • 33
  • 1
  • 4
  • If `c` is a `char` then `c += 2` is short for `c = (char) (c+2)`. That is how all the compound assignment operators work. – khelwood Jul 03 '16 at 19:33
  • 1
    Because this is how it is defined in [JLS Sec 15.26.2](https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.26.2). Unsatisfying as it may be as a response, it's just how the language defines the operator. – Andy Turner Jul 03 '16 at 19:34
  • The reason why the `char c = 5;` works is because `5` is a compile-time constant. Looking for the language spec reference... – Andy Turner Jul 03 '16 at 19:43
  • @AndyTurner but why does Java require you to cast these int to char values in the first place? – Simar Chhabra Jul 03 '16 at 19:53
  • Because it's a narrowing conversion. You also have to cast when assigning a ```long``` to an ```int``` for instance. There's a possible loss of data. – Jorn Vernee Jul 03 '16 at 20:13

0 Answers0