Core Java: A compound assignment operator hides an implicit narrowing cast

b += 300 compiles even though byte b = b + 300 would not, because compound assignment silently inserts a narrowing cast back to the variable's type; the same happens mixing a double into an int.

Code
byte b = 10;
b += 300;
System.out.println("byte 10 += 300 -> " + b);
int i = 10;
i += 3.9;
System.out.println("int 10 += 3.9 -> " + i);
Output
byte 10 += 300 -> 54
int 10 += 3.9 -> 13
Advertisement
More in JAVA

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-09-27

© Java Coding Hub · About · Contact · Privacy · Terms