• 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:
  • Tim Cooke
  • Campbell Ritchie
  • Ron McLeod
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Junilu Lacar
  • Rob Spoor
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Tim Moores
  • Jesse Silverman
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Piet Souris
  • Frits Walraven

String and StringBuffer equals method

 
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
Thanks
 
Ranch Hand
Posts: 98
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Vroummmmm
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
WHAT is your favorite color? Blue, no yellow, ahhhhhhh! Tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
reply
    Bookmark Topic Watch Topic
  • New Topic