Why do compound assignment operators +=, -=, *= in Java not require explicit type casting?
Hi everyone! I recently started learning Java and encountered some confusing behavior. Suppose I have this code:
```java
int a = 5;
long b = 10L;
a = a + b; // Compilation error: incompatible types: possible lossy conversion from long to int
```
This makes sense — Java requires explicit casting because `long` can be larger than `int`. But if I use a compound operator:
```java
int a = 5;
long b = 10L;
a += b; // Works without errors!
```
Why is that? Logically, `a += b` should be the same as `a = a + b`. But the compiler accepts the second version without casting, even though the types are the same. This confuses me because I thought Java strictly checks types. Please explain what's the trick here? Are there situations where this could lead to data loss or bugs?
No answers yet.
Log in to leave an answer
Blogs
Security of Java Applications: Top 10 Vulnerabilities in Practice
Why char[] is Better Than String for Passwords? A Code Guide
Working with the File System in C++: A Practical Guide
Generic or Associated Type in Rust: What to Choose in 2025?