Why is this an issue?

Casting expressions are utilized to convert one data type to another, such as transforming an integer into a string. This is especially crucial in strongly typed languages like C, C++, C#, Java, Python, and others.

However, there are instances where casting expressions are not needed. These include situations like:

These scenarios are considered unnecessary casting expressions. They can complicate the code and make it more difficult to understand, without offering any advantages.

As a result, it’s generally advised to avoid unnecessary casting expressions. Instead, rely on the language’s type system to ensure type safety and code clarity.

Exceptions

Casts from int to float, from long to float, and from long to double can document potential precision loss. Although Java performs these widening conversions implicitly, they can lose precision. This rule preserves casts that document awareness of potential precision loss, as required by {rule:java:S9395}. The cast does not prevent rounding or preserve the original value’s precision.

Compile-time constants between -224 and 224 (inclusive) for float, and between -253 and 253 (inclusive) for double, do not lose precision during conversion. Redundant casts of these constants are still reported.

class NumericConversions {
  void convert(int intValue, long longValue) {
    float first = (float) intValue; // Compliant
    float second = (float) longValue; // Compliant
    double third = (double) longValue; // Compliant
    float constant = (float) 1; // Noncompliant
  }
}

Casting may be required to distinguish the method to call in the case of overloading:

class A {}
class B extends A{}
class C {
  void fun(A a){}
  void fun(B b){}

  void foo() {
    B b = new B();
    fun(b);
    fun((A) b); // Compliant, required to call the first method so cast is not redundant.
  }
}

How to fix it

To fix your code remove the unnecessary casting expression.

Code examples

Noncompliant code example

class Example {
    public void example(List<String> list) {
        for (String item: (List<String>) list) {  // Noncompliant, Remove this unnecessary cast to "List".
          //...
        }
    }
}

Compliant solution

class Example {
    public void example() {
        for (String foo : getFoos()) {
          //...
        }
    }

    public List<String> getFoos() {
        return List.of("foo1", "foo2");
    }
}

Resources

Documentation

Related rules