Avatar ·

Why do compound assignment operators (+=, -=, *=) in Java not require explicit type casting?

Hi everyone! I just started learning Java and encountered behavior I don't understand. When I write a regular assignment, for example: int a = 5; a = a + 3.5; // Compilation error: loss of precision The compiler complains that double cannot be assigned to int without explicit casting. That makes sense. But if I use the compound operator +=: int a = 5; a += 3.5; // Works! Result is 8 Here I'm confused. Why doesn't the compiler require a cast in the second case? After all, the result of adding int and double is double, and we lose it when assigning to int. Logically, it should be like the first example — an error. Why is this? Is it a language feature or am I missing something? What are the pitfalls when using such operators? For example, what happens if I write: short s = 1; s += 1; // Works