What does incompatible types: possible lossy conversion mean in Java?
Why It Happens
Java enforces strict type checking to prevent accidental data loss. When you assign a double to an int, the fractional part would be truncated, so the compiler flags it as a possible lossy conversion. Similarly, assigning a long to an int or a float to a short triggers the same error.
This also occurs when you use a larger literal without a suffix, like int x = 10000000000; (which exceeds int range) or when you try to store a method result of a wider type into a narrower variable.
- Assigning a double or float to an int or long without a cast.
- Assigning a long to an int without a cast.
- Using an integer literal that's too large for the target type.
- Passing a wider type to a method parameter of a narrower type.
How to Resolve It
If you're sure the value fits and you accept truncation, add an explicit cast: int y = (int) someDouble;. For long to int, use (int) someLong. If the value might not fit, consider using a wider type like long or double instead.
For literals, add an L suffix for long (e.g., long x = 10000000000L;) or use a smaller value. Always check that the cast won't cause unexpected results, especially with negative numbers or rounding.
Common mistakes
- Thinking the error is just a warning—Java treats it as a compile-time error, so your code won't run.
- Casting without considering the actual value, leading to silent data corruption.
- Using float for precise decimal calculations when double is needed, causing precision loss.
Related questions
- What does TypeError: unsupported operand type(s) mean in Python?
- How do I fix cannot convert string to int in Java?
- What does undefined is not a function mean in JavaScript?
- Why do I get a type mismatch error in C++?
- How do I fix an implicit conversion error in C#?
- What does TS2339 Property does not exist on type mean in TypeScript?