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.
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:
Now let’s look at a few coding examples to see how exactly the equals
method works.
equals
with numeric valuesThe 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));}}
equals
with string valuesThe 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));}}
equals
with boolean valuesThe 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));}}
Free Resources