How to use the equals method in Java?

The equals method in Java is invoked every time an object is compared with another object to see if they are equivalent to each other or not i.e. are they the same object in terms of data type and value.

How is equals used?

The equals method is called as a method invoked by the object, as shown in the code snippet below.

No alt text provided for this image

The illustration below shows how this method works:


No alt text provided for this image

Examples

Now let’s look at a few coding examples to see how exactly the equals method works.

1. Using equals with numeric values

The example below shows how to see if two integer values are equal to each other or not.

No alt text provided for this image

2. Using equals with string values

The following example checks if the given two strings have the same value. Note that equals is case-sensitive and returns a value, true or false, only if the argument given does not have a NULL value

No alt text provided for this image

3. Using equals with boolean values

The following example evaluates a boolean logical equation and compares it to a given boolean value to check if they are equal.

No alt text provided for this image


To view or add a comment, sign in

Others also viewed

Explore topics