• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

string(buffer) comparision...

 
sam mathew
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I saw the following question in a mock exam site...
public class Test1 {
public static void main( String [] args ) {
StringBuffer sb1 = new StringBuffer("Amit");
StringBuffer sb2= new StringBuffer("Amit");
String ss1 = "Amit";
System.out.println(sb1==sb2);
System.out.println(sb1.equals(sb2));
System.out.println(sb1.equals(ss1));
System.out.println("Poddar".substring(3));
}
}
The result when I run this is false,false,false,dar..
But,what I expected was false,true,false,dar..
can someone clarify...
 
Aparna Narayanan
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Sam,
StringBuffer does not have any equals() method for itself. It inherits this method from that of java.lang.Object. The following is an extract taken from javadoc api specification:
The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any reference values x and y, this method returns true if and only if x and y refer to the same object (x==y has the value true).
So, sb1.equals(sb2) will return true only if both these point to the same object. Hence, when their references are the same, you will have the value "true" returned.
Hope this solves your problem.
Regds,
Aparna
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic