devxlogo

Use “.equals” in Place of “==”

Use “.equals” in Place of “==”

Java provides two methods to test for equality: the == Operator and the .equals method. The .equals is implemented by all objects. Most programmers tend to use == for equality, especially those with a C++ background. While this works fine with the basic data types (float, int, char etc.,), objects are a totally different cup of tea.

The == operator when used with objects tests whether the two references are pointing to the same object, while the .equals method implements can be used to check the equality of members rather than absolute equality. To add to the confusion, the default equals method, supplied by java.lang.Object, uses == to compare the objects.

Most classes override the default .equals method to do something more useful. For example The String class implements .equals to check whether the two objects have the same characters in the same order.

As a rule of thumb, use .equals as wherever it is implemented. It is implemented with a view to be used. If not implemented the default .equals functionality will use == for checking equality.

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist