• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Probelm in String Buffer

 
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
public class StringBuffercheck
{
public static void main(String args[])
{
StringBuffer s1= new StringBuffer("LALIT");
StringBuffer s2= new StringBuffer("LALIT");
if(s1.equals(s2))
System.out.println("Equal");
else
System.out.println("Not equal");

}
}

Why is it giving the result as "Not equal"?
How can we check for the equality of two string buffers?
I am confused?
Please help....
Thanks in advance
Lalit
 
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
you need to change your code like gien below.then it will give the output equal.
public class StringBuffercheck
{
public static void main(String args[])
{
StringBuffer s1= new StringBuffer("LALIT");
StringBuffer s2;//= new StringBuffer("LALIT");
s2= s1;
if(s1.equals(s2))
System.out.println("Equal");
else
System.out.println("Not equal");
}
}
Note : because equals method not defined in stringbuffer.this equals method belongs to class Object. this method compares only
object references
 
Lalit Goyal
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
[but than how come similar code compares two Strings?
Can you brief me with the diffrence in these two. I mean in this respect, how is stringBuffer diffrent from String?
 
Lalit Goyal
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
moreover if two string buffers are created this way(new stringBuffer) they will never be equal. Right?
Thanks for all the help
Lalit
 
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You could also solve this problem by using the toString() method of the StringBuffer to do the comparison.
<PRE>
if(s1.toString().equals(s2.toString())){
...
<PRE>
 
reply
    Bookmark Topic Watch Topic
  • New Topic