Skip to content
javahacks.dev
Java Core

Fix Java Uses Unchecked or Unsafe Operations Warning

Decode the Note about unchecked or unsafe operations, find the lines with Xlint, and fix raw types and casts instead of suppressing the warning.

6 min read
Summarize in AI
Flat illustration of an editor window full of code, with the OpenJDK, Spring, Gradle and JUnit5 logos.

The build succeeds and prints two lines of noise:

Text
Note: Main.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.

It is not an error, and that is the danger. The message marks a place where the compiler stopped checking generic types, and because generics are erased at run time, the check you skipped surfaces later as a [ClassCastException](/library/classcastexception-fix-heap-pollution-java) in code that looks perfectly correct. This guide finds the offending lines, sorts the causes by how often they occur and shows the fix for each. Examples compile on JDK 25.

Find the lines

Shell
javac -Xlint:unchecked Main.java
Text
Main.java:8: warning: [unchecked] unchecked call to add(E) as a member of the raw type List
        names.add("ada");
                 ^
  where E is a type-variable:
    E extends Object declared in interface List

Each warning names the file, line and the operation the compiler could not verify. Maven and Gradle take the same flag. In Maven put <compilerArgs><arg>-Xlint:unchecked</arg></compilerArgs> in the compiler plugin configuration, and in Gradle add options.compilerArgs.add("-Xlint:unchecked") to the JavaCompile task. Do this once for the whole project, so new warnings appear in the build log instead of hiding behind the two-line note.

Cause 1: a raw type

java
List names = new ArrayList();      // raw
names.add("ada");
names.add(42);                      // compiles, fails when read as String

A raw type is a generic class used without its type argument. The compiler lets you add anything, and the failure comes later when some other code reads the list as List<String> and reaches the integer. Supply the type argument and let the compiler enforce it.

java
List<String> names = new ArrayList<>();
names.add("ada");
// names.add(42);   is now a compile error

Old libraries sometimes return a raw type. Assign it to a typed variable in one place, with a short comment, instead of letting the raw type spread through the code.

Cause 2: an unchecked cast

java
Object value = cache.get(key);
List<String> list = (List<String>) value;     // unchecked cast

This cast checks only that value is a List. It cannot check what the list holds, because the type argument no longer exists at run time. If you control the code, change the declared types so the cast disappears, for instance by making the cache generic. If you cannot, validate the elements as you copy them.

java
static List<String> asStrings(Object value) {
    List<?> raw = (List<?>) value;
    List<String> out = new ArrayList<>(raw.size());
    for (Object o : raw) {
        out.add((String) o);      // each element is checked here
    }
    return out;
}

The copy costs time proportional to the list, and it turns a delayed failure into an immediate one at the boundary, which is where you want it.

Cause 3: generic arrays and varargs

new T[n] is not allowed, and (T[]) new Object[n] is an unchecked cast. Prefer a List<T>, or take a Class<T> parameter and call Array.newInstance. A varargs method with a generic element type, such as one taking List<String>..., warns about possible heap pollution at the declaration and at every call. If the method only reads from the array and never stores or exposes it, mark it @SafeVarargs. The annotation is only allowed on methods that cannot be overridden: static, final or private. More on this corner is in varargs and heap pollution.

Heap pollution in one example

It helps to see the delayed failure once.

java
List<String> strings = new ArrayList<>();
List raw = strings;
raw.add(42);                 // unchecked call, accepted
String s = strings.get(0);   // ClassCastException here

The exception points at the last line, which is correct code. The cause is two lines above. In a real service those lines may be in different modules and months apart, which is why the warning is worth fixing when it is cheap, at the point where it is raised.

Suppress only with a proof

Sometimes the cast is safe and cannot be expressed in the type system. A type-safe heterogeneous container is the classic case.

java
@SuppressWarnings("unchecked")   // handlers is only filled by register(), which stores Handler<T> under Class<T>
<T> Handler<T> find(Class<T> type) {
    return (Handler<T>) handlers.get(type);
}

Put the annotation on the narrowest declaration, a method or a local variable, never on a class. Write the comment that states why the cast cannot fail, so a reviewer can check the claim. A bare suppression is a promise nobody can verify.

Make the build enforce it

Once the existing warnings are fixed, stop new ones arriving. Compile with -Xlint:unchecked -Werror, or -Xlint:all -Werror if the project is clean enough. A warning that fails the build gets fixed the day it appears. A warning that only prints is added to the pile.

A short checklist for a legacy codebase

A project with hundreds of warnings does not need a weekend of fixing. Count them first with -Xlint:unchecked, group them by file, and start with the classes that sit at module boundaries, because a raw type at a boundary pollutes everything downstream. Fix the cause where it enters, usually one method that returns List or Map without arguments, and the warnings in its callers disappear. Leave generated code and test fixtures for last, and exclude generated sources from the lint flag so they do not drown out real findings.

Two habits keep the count at zero afterwards. Review any new @SuppressWarnings("unchecked") as a request for proof, and refuse a suppression on a class or a whole method that does more than the cast. A method that mixes an unchecked cast with ten lines of logic hides every later mistake in those ten lines.

What the compiler cannot see

Unchecked warnings concern generics, but the same pattern applies to casts through Object in serialisation, reflection and caches. A map from Class<?> to Object is safe only because every writer puts the right type in. If a cache is shared between modules, wrap the access in one typed method, so only a single place needs the justified cast and the rest of the code stays checked.

Wildcards instead of casts

Many unchecked casts exist because a method needed a concrete type argument it did not have. A method that only reads from a collection can take List<?> or List<? extends Number>, and the compiler then allows the reads without any cast. Changing a parameter from List<Object> to List<?> also lets callers pass a List<String>, which List<Object> rejects because generics are invariant. This is often the real fix: the cast was a symptom of a signature that was too narrow. The bounded forms are explained in PECS and bounded wildcards.

Where a cast is not the answer

Frameworks that deserialize into generic types need the full type, not a cast. In Jackson that is a TypeReference, as shown in fixing missing constructors, because List<Order> and List<Object> are the same class after erasure. The same family of mismatch appears in incompatible types. The rules are defined in the Java Language Specification on raw types, and the tutorial on raw types explains why they still exist: they keep pre-generics code compiling.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.