The equals() Method example in Java

By: Baski Emailed: 1729 times Printed: 2337 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

The equals() method compares two objects for equality and returns true if they are equal. The equals() method provided in the Object class uses the identity operator (==) to determine whether two objects are equal. For primitive data types, this gives the correct result. For objects, however, it does not. The equals() method provided by Object tests whether the object references are equal—that is, if the objects compared are the exact same object.

To test whether two objects are equal in the sense of equivalency (containing the same information), you must override the equals() method. Here is an example of a Book class that overrides equals():

public class Book {
    ...
    public boolean equals(Object obj) {
        if (obj instanceof Book)
            return ISBN.equals((Book)obj.getISBN()); 
        else
            return false;
    }
}

Consider this b that tests two instances of the Book class for equality:

Book firstBook  = new Book("0201914670"); //Swing Tutorial, 2nd edition
Book secondBook = new Book("0201914670");
if (firstBook.equals(secondBook)) {
    System.out.println("objects are equal");
} else {
    System.out.println("objects are not equal");
}

This program displays objects are equal even though firstBook and secondBook reference two distinct objects. They are considered equal because the objects compared contain the same ISBN number.

You should always override the equals() method if the identity operator is not appropriate for your class.


Note: If you override equals(), you must override hashb() as well.

Java Home | All Java Tutorials | Latest Java Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.



Bookmark and Share

Comments(4)


1. View Comment

Thanks for posting the JAVA source code!!

View Tutorial          By: Coder at 2010-07-29 11:41:10
2. View Comment

its show objects are not equal

View Tutorial          By: Amit at 2012-12-22 14:56:29
3. View Comment

Hi,

I think this is not a correct defination of equals method.
According to me correct definition is that

public class Book {
...
public boolean equals(Object obj) {
if(obj == null)
return false;
if(!(this == obj))
return false
if(getClass() != obj.getClass())
return ISBN.equals((Book)obj.getISBN());
else
return false;
}
}

Sorry if it have any errors...

DC :)


View Tutorial          By: Dinesh Chopra dc at 2013-03-19 04:30:48
4. View Comment

I'm a begner but i dont know the way to ask quistion by using google can any one help me?

View Tutorial          By: sajid kahn at 2013-05-23 19:15:26

Your name (required):


Your email(required, will not be shown to the public):


Your sites URL (optional):


Your comments:



More Tutorials by Baski
Compiling multiple source files and specifying classpath using javac
The equals() Method example in Java
Default Values for Data Types in Java
JSP Example to connect to MS SQL database using Tomcat Connection Pool
<convertNumber> and <convertDateTime> in JSF
Enable/Disable Scripting Elements in JSP
Using calloc() Function in C
lseek() sample program in C
Arrays of Structures example program in C
The Basic Syntax Expression Language in JSP
Initialization of Pointer Arrays in C
Functions returning non-integer values in C
Increment and Decrement Operators in C
Getting Started with C
What is JSF (JavaServer Faces)?

More Tutorials in Java
Update contents of a file within a jar file
Tomcat and httpd configured in port 8080 and 80
Java File
Java String
Count number of vowels, consonants and digits in a String in Java
Reverse a number in Java
Student marks calculation program in Java
Handling Fractions in Java
Calculate gross salary in Java
Calculate average sale of the week in Java
Vector in Java - Sample Program
MultiLevel Inheritance sample in Java
Multiple Inheritance sample in Java
Java program using Method Overriding
Java program to check if user input is an even number

More Latest News
Most Viewed Articles (in Java )
How to Send SMS using Java Program (full code sample included)
indexOf( ) and lastIndexOf( ) in Java
Student marks calculation program in Java
What is Java?
Method Overloading (function overloading) in Java
FileReader and FileWriter example program in Java
wait(), notify() and notifyAll() in Java - A tutorial
Vector example in Java
InetAddress Example program in Java
Method Overriding in Java
Calendar - sample program in Java
Hashtable example in Java
Sample Java program shows how to write to COM port using Java.
float vs double data types in Java
TreeMap example in Java
Most Emailed Articles (in Java)
Vector in Java - Sample Program
Use of return statement in Java
instanceof operator example in Java
3-D Secure Payment or 3DS - (3-Domain Secure Payment)
What is a Java Package and how to use it?
How to use Iterator in Java
J2EE Components
The java Buzzwords
The Basic Structure of a Simple Java program
Java Chat Client Sample Applet
MultiLevel Inheritance sample in Java
Taking the size of an Array at runtime & generate random numbers to populate the Array
What is JasperReports?
java.lang.reflect package
Applet Notinited : Applet xxxxxxxxxxxx notinited