Java Shot #1: The misapplication of equals() method in Java

One of the major advantages of statically typed language is to identify invalid data type comparisons at compile time.

Java is a statically typed language and that's one main reason why I like writing Java code but there are instances where it is not.

Today I talk about equals() method and how it's so easy to misapply this method.

Let's take a look at the equals() method signature from the javadoc.

public boolean equals(Object obj)

If you look at the argument to equals method, Object is the argument and this method is inherited from Object class which is root class which means you can call equals() method on any class.

Now, let's take an example of where this gets misapplied.

Comparing two different data type

class Main {
  public static void main(String[] args) {
    var a = Integer.valueOf(10);
    var b = Float.valueOf(10.0F);
    System.out.println(a.equals(b)); // this always returns false.

From the looks of it, this is a simple program and you can figure out what's wrong with this code.

Can you identify this in complex projects? To avoid this problem, Java projects can enable code analyzer tools like Sonar in their deployment pipeline.