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 Strings, StringBuffer and equals() 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 "Strings, StringBuffer and equals()" Watch "Strings, StringBuffer and equals()" New topic

Strings, StringBuffer and equals()


Joined: Jun 08, 2001
Posts: 4
Hi ! Can equals method be applied to StringBuffers ? can't it compare values of a String and StringBuffer? I ran the following code and got the answers as follows :
StringBuffer s7;
String s1 = new String("Usha");
String s2 = new String("Usha");
String s3 = "Usha";
String s4 = "Usha";
StringBuffer s5 = new StringBuffer("Usha");
StringBuffer s6 = new StringBuffer("Usha");
s7 = s6;
System.out.println("With ==");
if (s1==s2) { System.out.println("s1==s2");}
if (s3==s4) { System.out.println("s3==s4");}
if (s5==s6) { System.out.println("s5==s6");}
if (s1==s3) { System.out.println("s1==s3");}
if (s7==s6) { System.out.println("s7==s6");}
/* if (s3==s5) { System.out.println("s1==s2");}*/
System.out.println("With equals");
if (s1.equals(s2)) { System.out.println("s1.equals(s2)");}
if (s3.equals(s4)) { System.out.println("s3.equals(s4)");}
if (s5.equals(s6)) { System.out.println("s5.equals(s6)");}
if (s1.equals(s3)) { System.out.println("s1.equals(s3)");}
if (s1.equals(s5)) { System.out.println("s1.equals(s5)");}
if (s3.equals(s5)) { System.out.println("s3.equals(s5)");}
if (s7.equals(s6)) { System.out.println("s7.equals(s6)");}

The output I got was :
With ==
with equals

Here with equals, when it is comparing two string objects s1 and s2 it is returning true, and similarly it does compare StringBuffers,and gives true for s7 and s6. I know s6 and s7 point to the same reference. But why is it not comparing s5 and s6, similar to comparing s1 and s2 ? ie why is it not returning true?
Please ,can someone generally explain the working of equals()
and if it is used to compare the values in 2 objects, why can't it compare a String and StringBuffer. (the commented line gives a compiler error).
If this has already been discussed anywhere else in this forum, please give me the links also.
Thank you in advance
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
1. Search for StringBuffer using the "Search" facility in this forum.
2. StringBuffer does not override the equals() method. So any combination involving a string buffer and equals method will retrun false.
3. new String(string) or new StringBuffer(string) will always create a new object. Thus the comparision using the reference variables will always be false.

I agree. Here's the link:
subject: Strings, StringBuffer and equals()
jQuery in Action, 3rd edition