1

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?

Robb Hoff
  • 1,719
  • 2
  • 17
  • 32

1 Answers1

4

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
arshajii
  • 127,459
  • 24
  • 238
  • 287
  • thanks for the answer, do you know why `ch = ch + (char) 2;` doesn't also work? – Robb Hoff Mar 22 '14 at 14:06
  • 2
    @area5one Because the result of adding two chars is also an int. See http://stackoverflow.com/questions/8688668/in-java-is-the-result-of-the-addition-of-two-chars-an-int-or-a-char. – arshajii Mar 22 '14 at 14:09