Data conversion changes how a value is interpreted as another Java type. It can be implicit, as when integer arithmetic is widened for a floating-point context, or explicit through a cast. Casts are not merely documentation: narrowing numeric values can discard information, and reference casts can fail at runtime. Treat every conversion as a claim about the value’s range or actual type. section 4.7 section 5.3.1 section 4.3
Narrowing from long to int is especially risky. Values outside the int range lose their upper bits rather than producing a correct smaller representation. A file length above 2 GB, for example, may become negative; a still larger value may become a plausible but incorrect positive number. Prefer a checked conversion when the range is uncertain. section 4.7
Make a range check executable
Instead of passing a narrowed file size directly, use Math.toIntExact() when an int is genuinely required. It throws ArithmeticException for an out-of-range value, making an invalid assumption visible at the conversion point. If a direct cast is known to be safe, document the range invariant that makes it safe. section 4.7
Integer division is another conversion trap. In value / 2, both operands are integers, so the fractional part is discarded before assignment; assigning that result to double does not restore it. State the intended arithmetic with a floating-point operand or an explicit cast, and avoid var when inferred primitive types would hide that choice. section 4.3
For reference conversions, preserve static type information instead of relying on an unchecked assumption:
- Guard an explicit cast with instanceof, or use Java 16 pattern matching to test and bind the narrowed variable together. section 5.3.1
- If a method truly accepts only a concrete type, declare that concrete parameter type rather than accepting Object and casting immediately. section 5.3.1 section 5.5
- Avoid unchecked generic casts where possible: type erasure can postpone ClassCastException until a compiler-inserted cast at a later use site. section 5.5
- Use an explicit cast to resolve a one-argument varargs ambiguity, particularly around null, but choose whether null means an element or the array reference. section 2.9.1
// I want an array containing null printAll((Object)null); // I want just null array reference printAll((Object[])null);
These two casts encode different calls: one supplies a varargs array containing null; the other supplies a null array reference, which can fail inside the method. section 2.9.1
Static analysis can flag suspicious numeric casts and confusing varargs calls, but warnings need context: a narrowing cast may be range-safe, while an inspection can produce many harmless reports. Use tools to locate assumptions, then verify the value range and API contract rather than silencing or obeying every warning mechanically. section 2.9.1 section 4.7




















