Domanda

Hi I have a piece of Java code that shifts a character by 2, like so

char ch = 'A';
ch += 2;
System.out.println(ch);

The output in this case is 'C' (as expected). But if I rewrite the code like this:

char ch = 'A';
ch = ch + 2;
System.out.println(ch);

I get a compilation error 'Type mismatch: cannot convert from int to char'. Why is this happening, aren't the two assingments equal?

È stato utile?

Soluzione

It's a common misconception that X += Y is identical to X = X + Y. From JLS §15.26.2:

A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T) ((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once.

Notice that there is an implicit cast involved. Now when you have something like:

ch = ch + 2;  // no cast, error

the type of the right-hand side is int while the type of the left-hand side is char, so there is a type mismatch between the two sides of the assignment, hence the error. This can be fixed with an explicit cast:

ch = (char) (ch + 2);  // cast, no error
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top