0
char c = 'c';
int x = 10;

Here is my problem: when I write c = c+x; I have an error and the solution is casting c = (char) (c+x); but when I write c+=x; without casting I have no error.

And the output after c = (char) (c+x); System.out.println(c+x); is m but the output after System.out.println(c+x); is 119

What difference between c+=x; and c = c + x; in java

jackop
  • 1
  • 1

2 Answers2

2

The type of c + x is int, so you can't assign it back to a char.

System.out.println((char) (c + x)) invokes the PrintStream.println(char) overload, so it prints as a char.

System.out.println(c + x) invokes the PrintStream.println(int) overload, so it prints as an int.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
1

It's just how compound assignment operators like += are defined.

See this:

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

In your case the type of c is char, so the cast to a char is implicit when you write c+=x.

Paul Boddington
  • 37,127
  • 10
  • 65
  • 116