File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes String and StringBuffer equals method Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "String and StringBuffer equals method" Watch "String and StringBuffer equals method" New topic

String and StringBuffer equals method


Joined: Apr 30, 2000
Posts: 9
It seems like I have missed a point in my lecture somewhere and I have difficulty to understand the following test I have done with the equal method.
Let see my code:
Line 1 StringBuffer sb1 = new StringBuffer("JAVA");
Line 2 StringBuffer sb2 = new StringBuffer("JAVA");
Line 3 System.out.println( sb1.equals(sb2)); //false

Line 4 String s1 = new String("JAVA");
Line 5 String s2 = new String("JAVA");
Line 6 System.out.println( s1.equals(s2)); //true
What I was expecting the same result in line 3 and 6. Could you give me an advice of where I can go for fixing my inquiry.

French is my language, Java is my passion
Surya B
Ranch Hand

Joined: May 10, 2000
Posts: 98
StringBuffer class does not override the equals method of the object class,so when you say
System.out.println( sb1.equals(sb2));
it prints out false since the equals method of the Object gets called.
To quote from Java API:
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).
In case of String class it overrides the equals method of the Object class and this returns true if the String are equal otherwise false .So thats why s1.equals(s2)) prints true.

Joined: Apr 30, 2000
Posts: 9
Thanks I get it.
I've try this way to get it.
System.out.println( sb1.toString().equals(sb2.toString()));

Again guys, out there taking care of those questions let me say that I appreciate a lot.
I agree. Here's the link:
subject: String and StringBuffer equals method
It's not a secret anymore!