Trusted answers to developer questions

How to use the equals method in Java

Get Started With Machine Learning

Learn the fundamentals of Machine Learning with this free course. Future-proof your career by adding ML skills to your toolkit — or prepare to land a job in AI or Data Science.

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.

class HelloWorld {
public static void main( String args[] ) {
( object_one ).equals( object_two )
}
}

The illustration below shows how this method works:

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.

class numberEquals {
public static void main( String args[] ) {
Integer number_one = 5;
Integer number_two = 6;
Integer number_three = 5;
System.out.print(number_one.equals(number_two) + "\n");
System.out.print(number_one.equals(number_three));
}
}

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

class stringEquals {
public static void main( String args[] ) {
String str_one = "hello";
String str_two = "Hello";
String str_three = "hello";
System.out.print(str_one.equals(str_two) + "\n");
System.out.print(str_one.equals(str_three));
}
}

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.

class boolEquals {
public static void main( String args[] ) {
Boolean bool_one = true;
Boolean bool_two = false;
System.out.print(bool_one.equals(bool_two || bool_one) + "\n");
System.out.print(bool_one.equals(bool_two));
}
}

RELATED TAGS

compare
java
equal
comparison operators
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?