Given:public class Main {
public static void main(String[] args) {
short s = 100;
s += 32700;
System.out.println(s);
}
}What is the result?
Choose one.
A compound assignment E1 op= E2 is equivalent to E1 = (T) ((E1) op (E2)), where T is the type of E1.
The addition is done in int (32800), and the hidden cast to short keeps only the low 16 bits, giving -32736. The tempting answers either forget the hidden cast (compile failure) or forget that the cast can overflow (32800). Narrowing never throws.
- Rewrite s += 32700 as s = (short) (s + 32700).
- Compute the int sum: 32800.
- Compare with the short range -32768 to 32767: it does not fit.
- Wrap: 32800 - 65536 = -32736.
Exam tip: op= hides a cast to the variable's type, so it compiles where the long form fails, and it can overflow silently.
Java Primitives, Wrapper Classes, Operators and Casting (1Z0-831) — the lesson that teaches this.