> ## Content Index
> Fetch the complete content index at: https://www.narendravardi.com/llms.txt
> Use this file to discover other available public pages before exploring further.

# Java Shot #1: The misapplication of equals() method in Java
- URL: https://www.narendravardi.com/the-misapplication-of-equals-method-in-java/
- Published: 2024-06-15T10:30:36.000Z
- Updated: 2024-12-02T08:45:00.000Z
- Author: Narendra Vardi
- Tags: java-shot, 2024

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](https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html?ref=narendravardi.com#equals-java.lang.Object-).

```Java
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**

```Java
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](https://docs.sonarsource.com/sonarqube/latest/analyzing-source-code/languages/java/?ref=narendravardi.com) in their deployment pipeline.