Recipe Name:
Invalid comparison of String to number wrapper
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.

Before
boolean areEqual = "123".equals(123);
After
boolean areEqual = false;
Recipe
id: scw:java:equality-string-number-wrapper
version: 10
metadata:
  name: Invalid comparison of String to number wrapper
  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: java\.lang\.(Float|Integer|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: Parse string to number
  actions:
  - rewrite:
      to: '{{{arguments.0.qualifier}}}.valueOf({{{qualifier}}}).equals({{{arguments.0}}})'
- name: Replace comparison with false
  actions:
  - rewrite:
      to: "false"