# Remove Redundant Type Casts

# Description

The rule first searches the next type-cast operation. If the expression is casted to a type which already is exactly the type of the expression, then the type casting expression is removed. Additionally, also parentheses involved in the cast operation will be removed if they are not necessary any more. This rule regards two types as exactly the same only when both types have also exactly the same generic arguments.

# Benefits

This rule increases readability by removing redundant code.

# Tags

# Code Changes

# Type cast on string literal





# Type cast on string variable


String helloWorld = "HelloWorld";


String helloWorld = "HelloWorld";

# Type cast on List of String


List<String> l = new ArrayList<>();


List<String> l = new ArrayList<>();

# Type cast combined with unnecessary parentheses


long x = ((((long)((long)((100 + 200L)) + 300))));


long x = ((100 + 200L)) + 300;

# Limitations

# Casting expressions using wild cards

It is not safe to remove type casts containing wild cards (?). E.g.:

Not Transformed

List<?> l = new ArrayList<>();

# Casting lambda expressions to Object

Lambda expressions are not subtypes of Object and therefore implicit casting is not possible. E.g.:

Not Transformed

Object object = (Supplier<String>) () -> "";

🛠️ Auto-refactor Available

You can auto-refactor this with jSparrow.
Drop this button to your Eclipse IDE workspace to install jSparrow for free:

Drag to your running Eclipse* workspace. *Requires Eclipse Marketplace Client

Need help? Check out our installation guide.

# Properties

Property Value
Rule ID RemoveRedundantTypeCast
First seen in jSparrow version 3.15.0
Minimum Java version 1.1
Remediation cost 5 min