The equals() Method example in Java

By: Baski Emailed: 1605 times Printed: 2077 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 )
XML and Java - Parsing XML using Java Tutorial
Read from a COM port using Java program
FileReader and FileWriter example program in Java
Integer: byte, short, int, and long data types in Java
Count number of vowels, consonants and digits in a String in Java
indexOf( ) and lastIndexOf( ) in Java
How to Send SMS using Java Program (full code sample included)
Student marks calculation program in Java
Calculate gross salary in Java
append() in Java
How to use Iterator in Java
Recursion in java
Vector example in Java
Stack example in Java - push(), pop(), empty(), search()
Reading from a file and writing to a file using Java program
Most Emailed Articles (in Java)
What is Java?
How to Send SMS using Java Program (full code sample included)
inheritance in Java
Handling Fractions in Java
Summary of Operators in Java
Use of return statement in Java
Booleans in java
emulator 0 terminated while waiting for it to register!
FileReader and FileWriter example program in Java
The java Buzzwords
Execute system commands in a Java Program
Update contents of a file within a jar file
package com.sun.speech.freetts does not exist.
The clone() Method in Java
instanceof sample program in Java