Quick Answer

Handle narrowing conversions safely.

Understanding the Issue

Occurs when assigning wider primitive type to narrower without explicit cast. Java protects against accidental data loss.

The Problem

This code demonstrates the issue:

Java Error
double d = 3.14;
int i = d; // Error

The Solution

Here's the corrected code:

Java Fixed
// Solution 1: Explicit cast
int i = (int)d; // Truncates decimal

// Solution 2: Use Math.round
long l = Math.round(d);

// Solution 3: Check bounds
if (d >= Integer.MIN_VALUE && d <= Integer.MAX_VALUE) {
    i = (int)d;
}

Key Takeaways

Always be explicit about narrowing conversions.