Recipe Name:
Invalid comparison of String to number primitive
Description:
This comparison of a String to a number will always return false
Level:
error
Language:
- java
Tags:
- Java basic
- quality
Documentation
Comparing a String to a primitive using equals
will always return false.
The first check performed by the equals
method is a checking whether the String and object it is compared to are of the same type. This check will always fail as primitives and Strings have different types. Therefore, the comparison can be replaced with false
.
boolean areEqual = "123".equals(123);After
boolean areEqual = false;
Recipe
id: scw:java:equality-string-number-primitive version: 10 metadata: name: Invalid comparison of String to number primitive shortDescription: This comparison of a String to a number will always return false level: error language: java scwCategory: blog:generic cweCategory: 480 enabled: true descriptionFile: descriptions/Comparison_of_String_to_number_primitive.html tags: Java basic;quality search: methodcall: args: 1: type: reference: matches: (float|int|long|short|double) checkInheritance: true name: equals type: java.lang.String availableFixes: - name: Compare number as string actions: - modifyArguments: rewrite: 1: java.lang.String.valueOf({{{.}}}) - name: Replace comparison with false actions: - rewrite: to: "false"