0

I wrote two versions of Java code to increment a char variable by 1:

version1:

char c = 'a';
c = c + 1;

version2:

char c = 'a';
c += 1;

To my surprise, the second version compiles and runs successfully but the first one shows an error, which says incompatible types: lossy conversion from int to char. Why are they different?

Gropai
  • 321
  • 1
  • 2
  • 11

1 Answers1

2

The second version involves a cast, and is equivalent to:

c = (char) (c + 1);

See JLS section 15.26.2 (Compound operators):

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.

nanofarad
  • 40,330
  • 4
  • 86
  • 117
  • I've seen someone post questions using the first version, and the code runs too. Why do we get different results?See here: http://stackoverflow.com/questions/17124992/incrementing-char-type-in-java – Gropai Feb 13 '16 at 01:26
  • @Gropai I cannot reproduce that behavior. I get the loss of precision warning in Java9 jShell and Java 8 javac. – nanofarad Feb 13 '16 at 01:28