Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

equals and instanceof

 
Syed Naimathullah
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi friends, can you just explain what "equals" and "instanceof" used for.what is the difference between them.
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Moved here from SCJP. This level of question belongs here.
 
Chandra Bhatt
Ranch Hand
Posts: 1710
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public boolean equals(Object o)
It is method defined in the Object class. equals() main concern to compare
whether two objects are meaningfully equal or not.

Person p1 = new Person("Mack");
Person p2 = new Person("Mack");

Here p1 and p2 can be considered meaningfully equivalent because both
objects encapsulate the same name "Mack". But for this to take place you
need to override the equals() method of the Object class in the Person class
otherwise you will get the default behavior of the equals() of the Object,
because every class inherits Object class methods.

Default behavior of equals(): Object class equals() does nothing
special but returns true if both references refer to the same object on
the heap. So it is same as you do p1==p2.

instanceof This is Java operator used to test whether a particular
object is an instance of given class.
You can use instanceof operator in this way:

 
Pravin Jain
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
instanceof could be used to test not only class but for any reference type
including arrays and interfaces.
 
Pravin Jain
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
two things could be equals but not necessarily same.

equals is for testing if two objects are equal
whereas == is for testing if they are same.
 
Ulf Dittmer
Rancher
Posts: 42968
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
instanceof could be used to test not only class but for any reference type including arrays and interfaces


... and in particular to test any class that (directly or indirectly) extends Person.
 
Pravin Jain
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The test is on an instance at run time being of a particular type
or its subtype. (All classes implementing an interface are sub-types
of the interface type and all classes and interfaces and array types are
subtypes of Object).
If the reference is null then it would always return false.

Person p1 = null;
if (p1 instanceof Person) { // false

}

int[] a = new int[10];
if (a instanceof Object) { // true

}
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic