The equals() Method example in Java

By: Baski Emailed: 1768 times Printed: 2516 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 use ArrayList in Java
InetAddress Example program in Java
FileReader and FileWriter example program in Java
Method Overloading (function overloading) in Java
Student marks calculation program in Java
Simple Port Scanner application using Java
Read from a COM port using Java program
Calculate gross salary in Java
delete() and deleteCharAt() in Java
append() in Java
indexOf( ) and lastIndexOf( ) in Java
XML and Java - Parsing XML using Java Tutorial
Vector in Java - Sample Program
The equals() Method example in Java
Using PrintWriter in Java
Most Emailed Articles (in Java)
Using Charts in JasperReports
Introducing Nested and Inner Classes
Increment and Decrement Operator
Tomcat and httpd configured in port 8080 and 80
List all the serial and parallel ports in your system using Java
What is Unicode?
StreamTokenizer sample program in Java
FileReader and FileWriter example program in Java
FilenameFilter - sample program in Java
Transient vs Volatile modifiers in Java
Basics of Inheritance in Java
Method Overloading (function overloading) in Java
while - Iteration in java
how to use boolean data type in Java
equals( ) Versus == in Java