java compile_error ai_generated true

error: incompatible types

ID: java/incompatible-types

Also available as: JSON · Markdown
95%Fix Rate
96%Confidence
90Evidence
2023-01-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
17 active

Root Cause

The 'incompatible types' compilation error occurs when the Java compiler detects a type mismatch — assigning a value of one type to a variable of an incompatible type without an explicit cast. The compiler message shows 'required: X, found: Y'.

generic

Workarounds

  1. 95% success Read the 'required' and 'found' types in the error message and fix the type mismatch at the source
    1. The compiler error shows 'required: X' (what the variable/parameter expects) and 'found: Y' (what was actually provided). 2. Common cases: returning wrong type from a method (fix the return statement or method signature), passing wrong argument type (convert or use the correct variable), assigning incompatible types (use proper conversion methods). 3. For primitives: use Integer.parseInt(), Long.valueOf(), etc. for String-to-number conversion. 4. For generics: ensure generic type parameters are consistent throughout the call chain.
  2. 90% success Use proper type conversion methods or redesign the API to use the correct types
    1. For String to numeric: Integer.parseInt(str), Double.parseDouble(str). 2. For numeric widening: int to long is automatic, but long to int requires (int) cast or Math.toIntExact(). 3. For collections: List<Integer> to List<Number> requires List.copyOf() or a new list — generics are invariant. 4. For Optional: use .map(), .flatMap(), .orElse() to transform types safely. 5. If the type mismatch reveals a design problem, refactor the interface to use the correct types rather than casting.

Dead Ends

Common approaches that don't work:

  1. Adding an explicit cast without verifying that the cast is semantically correct 55% fail

    Forcing a cast may compile, but if the types are genuinely incompatible at runtime, it will throw ClassCastException. For example, casting Object to String compiles but fails at runtime if the object is actually an Integer. The compiler error is protecting you from a runtime error.

  2. Changing the variable type to Object to accept any value 70% fail

    Using Object as the variable type eliminates the compilation error but discards type safety. Every subsequent use of the variable requires a cast, moving the error from compile time to runtime. This is a regression to pre-generics Java and defeats the purpose of the type system.

Error Chain

Leads to:
Preceded by:
Frequently confused with: