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

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