# Use equals() on Primitive Objects

# 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.

# Tags

# 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)) {
}

🛠️ 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 PrimitiveObjectUseEquals
First seen in jSparrow version 2.2.0
Minimum Java version 1.1
Remediation cost 2 min