Use equals() on Primitive Objects

Properties

Property Value
First seen in jSparrow version 2.2.0
Minimum Java version 1.1
Remediation cost 2 min

Description

This rule replaces the infix operators "==" and "!=" with equals() when used on primitive objects. The following types are considered primitive:

  • java.lang.Byte
  • java.lang.Char
  • java.lang.Short
  • java.lang.Integer
  • java.lang.Long
  • java.lang.float
  • java.lang.Double
  • java.lang.Boolean
  • java.lang.String

Benefits

If the equals method was overwritten on the instances being compared the == has a different meaning than using equals. This may lead to programming errors. Applying this rule means keeping with the coding conventions and thus helps avoid errors.

Requirement & Tags

Requirements

None

Code Changes

Pre

Integer a = new Integer(1);
Integer b = new Integer(2);

if (a == b) {
}

if (a != b) {
}

Post

Integer a = new Integer(1);
Integer b = new Integer(2);

if (a.equals(b)) {
}

if (!a.equals(b)) {
}

Automatic Application of This Rule

The automatic application of this rule is supported in the following jSparrow version: