# 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>) () -> "";

Use a Java Refactoring Tool

No license required

You can review this refactoring on your code without a license by installing jSparrow to your Eclipse IDE. Install the plug-in from Eclipse IDE: Eclipse Marketplace.

System-wide Refactoring

Do you want to automate this refactoring (and many more) to your system-wide code? The automatic application of this system-wide refactoring can be unlocked by acquiring your jSparrow license.

a drawn cute bird pointing at a graph that shows positive results

# Properties

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