0

Java is doing something here that I don't understand. If I have

int sum = 0;
long num = 1234;

Using the assignment operator += will work fine

sum += num % 10;

However, using simple assignment will cause a "Cannot convert long to int" error

sum = sum + num % 10;

Why is this ??

Paddykool
  • 15
  • 2
  • 6
  • This is maybe the better (or at least the more common) duplicate: [Java += operator](http://stackoverflow.com/questions/8710619/java-operator). – Tom Oct 02 '15 at 10:53

1 Answers1

2

When you do += that's a compound assignment and compiler internally have some mechanism to evaluate it. Where as in first case the compiler given an error since it normal statement.

JSL on how it treats compound assignment.

http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.26.2

In your first case, compiler translate your code to

sum += (int) (num % 10);

So there is a cast internally by compiler. Hence you are not prompted to an error. Compiler doing your job there :)

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307