Originally posted by Vivek Shrivastava:
HI,
Let me try to help u.
java.lang.Object Class contain
public boolean equals(Object obj) method and this class is the root of every class hierarchy.
So every class in java inherited this method. Every class should provide an appropriate implementation for the method otherwise that class would use the Object class version of the method. That simple check for two references and return true only if both the references are pointing to same object. Small example
public class Test{
public static void main(String arg[]){
Test a = new Test();
Test b = new Test();
System.out.println(a.equals(b)); //print false
a=b;
System.out.println(a.equals(b)); //print true
}
}
So for this case class Test is inherited from(implicitly) Object class and didn�t override the equals() method. So it is using Object class version of method.
First statement prints false because both references are pointing to different object.
Second statement prints true because both references are pointing to different object.
String class does provide a proper implementaion of equals() method and return true if the the content of both the String object is same or both the String Object is pointing to same object. Small example :
public class Test{
public static void main(String arg[]){
Test a = new String(�vivek�);
Test b = new String (�vivek�);
Test c = new String (�vivek1�);
System.out.println(a.equals(b)); //print true
System.out.println(c.equals(b)); //print false
b=c;
System.out.println(c.equals(b)); //print true
}
}
StringBuffer class does not provide a proper implementaion of equals() method and uses the Object class version and return false even the content of both variable is same because it is using Object class version of equals method which only check for two refrences not the content. It will return true only when both the refrences pointing to same object
public class Test{
public static void main(String arg[]){
Test a = new StringBuffer(�vivek�);
Test b = new StringBuffer(�vivek�);
System.out.println(a.equals(b)); //print false
b=a;
System.out.println(a.equals(b)); //print true
}
}
Hope this will help u.
java expert please feel free to correct me because I am trying to learn by giving answer of the question.
vivek